repository_name
stringclasses 316
values | func_path_in_repository
stringlengths 6
223
| func_name
stringlengths 1
134
| language
stringclasses 1
value | func_code_string
stringlengths 57
65.5k
| func_documentation_string
stringlengths 1
46.3k
| split_name
stringclasses 1
value | func_code_url
stringlengths 91
315
| called_functions
listlengths 1
156
⌀ | enclosing_scope
stringlengths 2
1.48M
|
|---|---|---|---|---|---|---|---|---|---|
saltstack/salt
|
salt/log/setup.py
|
__remove_temp_logging_handler
|
python
|
def __remove_temp_logging_handler():
'''
This function will run once logging has been configured. It just removes
the temporary stream Handler from the logging handlers.
'''
if is_logging_configured():
# In this case, the temporary logging handler has been removed, return!
return
# This should already be done, but...
__remove_null_logging_handler()
root_logger = logging.getLogger()
global LOGGING_TEMP_HANDLER
for handler in root_logger.handlers:
if handler is LOGGING_TEMP_HANDLER:
root_logger.removeHandler(LOGGING_TEMP_HANDLER)
# Redefine the null handler to None so it can be garbage collected
LOGGING_TEMP_HANDLER = None
break
if sys.version_info >= (2, 7):
# Python versions >= 2.7 allow warnings to be redirected to the logging
# system now that it's configured. Let's enable it.
logging.captureWarnings(True)
|
This function will run once logging has been configured. It just removes
the temporary stream Handler from the logging handlers.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/setup.py#L1172-L1197
|
[
"def is_logging_configured():\n return __CONSOLE_CONFIGURED or __LOGFILE_CONFIGURED\n"
] |
# -*- coding: utf-8 -*-
'''
:codeauthor: Pedro Algarvio (pedro@algarvio.me)
salt.log.setup
~~~~~~~~~~~~~~
This is where Salt's logging gets set up.
This module should be imported as soon as possible, preferably the first
module salt or any salt depending library imports so any new logging
logger instance uses our ``salt.log.setup.SaltLoggingClass``.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import re
import sys
import time
import types
import socket
import logging
import logging.handlers
import traceback
import multiprocessing
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse # pylint: disable=import-error,no-name-in-module
# Let's define these custom logging levels before importing the salt.log.mixins
# since they will be used there
PROFILE = logging.PROFILE = 15
TRACE = logging.TRACE = 5
GARBAGE = logging.GARBAGE = 1
QUIET = logging.QUIET = 1000
# Import salt libs
from salt.textformat import TextFormat
from salt.log.handlers import (TemporaryLoggingHandler,
StreamHandler,
SysLogHandler,
FileHandler,
WatchedFileHandler,
RotatingFileHandler,
QueueHandler)
from salt.log.mixins import LoggingMixInMeta, NewStyleClassMixIn
from salt.utils.ctx import RequestContext
LOG_LEVELS = {
'all': logging.NOTSET,
'debug': logging.DEBUG,
'error': logging.ERROR,
'critical': logging.CRITICAL,
'garbage': GARBAGE,
'info': logging.INFO,
'profile': PROFILE,
'quiet': QUIET,
'trace': TRACE,
'warning': logging.WARNING,
}
LOG_VALUES_TO_LEVELS = dict((v, k) for (k, v) in LOG_LEVELS.items())
LOG_COLORS = {
'levels': {
'QUIET': TextFormat('reset'),
'CRITICAL': TextFormat('bold', 'red'),
'ERROR': TextFormat('bold', 'red'),
'WARNING': TextFormat('bold', 'yellow'),
'INFO': TextFormat('bold', 'green'),
'PROFILE': TextFormat('bold', 'cyan'),
'DEBUG': TextFormat('bold', 'cyan'),
'TRACE': TextFormat('bold', 'magenta'),
'GARBAGE': TextFormat('bold', 'blue'),
'NOTSET': TextFormat('reset'),
'SUBDEBUG': TextFormat('bold', 'cyan'), # used by multiprocessing.log_to_stderr()
'SUBWARNING': TextFormat('bold', 'yellow'), # used by multiprocessing.log_to_stderr()
},
'msgs': {
'QUIET': TextFormat('reset'),
'CRITICAL': TextFormat('bold', 'red'),
'ERROR': TextFormat('red'),
'WARNING': TextFormat('yellow'),
'INFO': TextFormat('green'),
'PROFILE': TextFormat('bold', 'cyan'),
'DEBUG': TextFormat('cyan'),
'TRACE': TextFormat('magenta'),
'GARBAGE': TextFormat('blue'),
'NOTSET': TextFormat('reset'),
'SUBDEBUG': TextFormat('bold', 'cyan'), # used by multiprocessing.log_to_stderr()
'SUBWARNING': TextFormat('bold', 'yellow'), # used by multiprocessing.log_to_stderr()
},
'name': TextFormat('bold', 'green'),
'process': TextFormat('bold', 'blue'),
}
# Make a list of log level names sorted by log level
SORTED_LEVEL_NAMES = [
l[0] for l in sorted(six.iteritems(LOG_LEVELS), key=lambda x: x[1])
]
# Store an instance of the current logging logger class
LOGGING_LOGGER_CLASS = logging.getLoggerClass()
MODNAME_PATTERN = re.compile(r'(?P<name>%%\(name\)(?:\-(?P<digits>[\d]+))?s)')
__CONSOLE_CONFIGURED = False
__LOGGING_CONSOLE_HANDLER = None
__LOGFILE_CONFIGURED = False
__LOGGING_LOGFILE_HANDLER = None
__TEMP_LOGGING_CONFIGURED = False
__EXTERNAL_LOGGERS_CONFIGURED = False
__MP_LOGGING_LISTENER_CONFIGURED = False
__MP_LOGGING_CONFIGURED = False
__MP_LOGGING_QUEUE = None
__MP_LOGGING_LEVEL = GARBAGE
__MP_LOGGING_QUEUE_PROCESS = None
__MP_LOGGING_QUEUE_HANDLER = None
__MP_IN_MAINPROCESS = multiprocessing.current_process().name == 'MainProcess'
__MP_MAINPROCESS_ID = None
class __NullLoggingHandler(TemporaryLoggingHandler):
'''
This class exists just to better identify which temporary logging
handler is being used for what.
'''
class __StoreLoggingHandler(TemporaryLoggingHandler):
'''
This class exists just to better identify which temporary logging
handler is being used for what.
'''
def is_console_configured():
return __CONSOLE_CONFIGURED
def is_logfile_configured():
return __LOGFILE_CONFIGURED
def is_logging_configured():
return __CONSOLE_CONFIGURED or __LOGFILE_CONFIGURED
def is_temp_logging_configured():
return __TEMP_LOGGING_CONFIGURED
def is_mp_logging_listener_configured():
return __MP_LOGGING_LISTENER_CONFIGURED
def is_mp_logging_configured():
return __MP_LOGGING_LISTENER_CONFIGURED
def is_extended_logging_configured():
return __EXTERNAL_LOGGERS_CONFIGURED
# Store a reference to the temporary queue logging handler
LOGGING_NULL_HANDLER = __NullLoggingHandler(logging.WARNING)
# Store a reference to the temporary console logger
LOGGING_TEMP_HANDLER = StreamHandler(sys.stderr)
# Store a reference to the "storing" logging handler
LOGGING_STORE_HANDLER = __StoreLoggingHandler()
class SaltLogQueueHandler(QueueHandler):
pass
class SaltLogRecord(logging.LogRecord):
def __init__(self, *args, **kwargs):
logging.LogRecord.__init__(self, *args, **kwargs)
# pylint: disable=E1321
self.bracketname = '[%-17s]' % self.name
self.bracketlevel = '[%-8s]' % self.levelname
self.bracketprocess = '[%5s]' % self.process
# pylint: enable=E1321
class SaltColorLogRecord(SaltLogRecord):
def __init__(self, *args, **kwargs):
SaltLogRecord.__init__(self, *args, **kwargs)
reset = TextFormat('reset')
clevel = LOG_COLORS['levels'].get(self.levelname, reset)
cmsg = LOG_COLORS['msgs'].get(self.levelname, reset)
# pylint: disable=E1321
self.colorname = '%s[%-17s]%s' % (LOG_COLORS['name'],
self.name,
reset)
self.colorlevel = '%s[%-8s]%s' % (clevel,
self.levelname,
reset)
self.colorprocess = '%s[%5s]%s' % (LOG_COLORS['process'],
self.process,
reset)
self.colormsg = '%s%s%s' % (cmsg, self.getMessage(), reset)
# pylint: enable=E1321
_LOG_RECORD_FACTORY = SaltLogRecord
def setLogRecordFactory(factory):
'''
Set the factory to be used when instantiating a log record.
:param factory: A callable which will be called to instantiate
a log record.
'''
global _LOG_RECORD_FACTORY
_LOG_RECORD_FACTORY = factory
def getLogRecordFactory():
'''
Return the factory to be used when instantiating a log record.
'''
return _LOG_RECORD_FACTORY
setLogRecordFactory(SaltLogRecord)
class SaltLoggingClass(six.with_metaclass(LoggingMixInMeta, LOGGING_LOGGER_CLASS, NewStyleClassMixIn)):
def __new__(cls, *args): # pylint: disable=W0613,E0012
'''
We override `__new__` in our logging logger class in order to provide
some additional features like expand the module name padding if length
is being used, and also some Unicode fixes.
This code overhead will only be executed when the class is
instantiated, i.e.:
logging.getLogger(__name__)
'''
instance = super(SaltLoggingClass, cls).__new__(cls)
try:
max_logger_length = len(max(
list(logging.Logger.manager.loggerDict), key=len
))
for handler in logging.root.handlers:
if handler in (LOGGING_NULL_HANDLER,
LOGGING_STORE_HANDLER,
LOGGING_TEMP_HANDLER):
continue
formatter = handler.formatter
if not formatter:
continue
if not handler.lock:
handler.createLock()
handler.acquire()
fmt = formatter._fmt.replace('%', '%%')
match = MODNAME_PATTERN.search(fmt)
if not match:
# Not matched. Release handler and return.
handler.release()
return instance
if 'digits' not in match.groupdict():
# No digits group. Release handler and return.
handler.release()
return instance
digits = match.group('digits')
if not digits or not (digits and digits.isdigit()):
# No valid digits. Release handler and return.
handler.release()
return instance
if int(digits) < max_logger_length:
# Formatter digits value is lower than current max, update.
fmt = fmt.replace(match.group('name'), '%%(name)-%ds')
formatter = logging.Formatter(
fmt % max_logger_length,
datefmt=formatter.datefmt
)
handler.setFormatter(formatter)
handler.release()
except ValueError:
# There are no registered loggers yet
pass
return instance
def _log(self, level, msg, args, exc_info=None, extra=None, # pylint: disable=arguments-differ
exc_info_on_loglevel=None):
# If both exc_info and exc_info_on_loglevel are both passed, let's fail
if extra is None:
extra = {}
current_jid = RequestContext.current.get('data', {}).get('jid', None)
log_fmt_jid = RequestContext.current.get('opts', {}).get('log_fmt_jid', None)
if current_jid is not None:
extra['jid'] = current_jid
if log_fmt_jid is not None:
extra['log_fmt_jid'] = log_fmt_jid
if exc_info and exc_info_on_loglevel:
raise RuntimeError(
'Only one of \'exc_info\' and \'exc_info_on_loglevel\' is '
'permitted'
)
if exc_info_on_loglevel is not None:
if isinstance(exc_info_on_loglevel, six.string_types):
exc_info_on_loglevel = LOG_LEVELS.get(exc_info_on_loglevel,
logging.ERROR)
elif not isinstance(exc_info_on_loglevel, int):
raise RuntimeError(
'The value of \'exc_info_on_loglevel\' needs to be a '
'logging level or a logging level name, not \'{0}\''
.format(exc_info_on_loglevel)
)
if extra is None:
extra = {'exc_info_on_loglevel': exc_info_on_loglevel}
else:
extra['exc_info_on_loglevel'] = exc_info_on_loglevel
LOGGING_LOGGER_CLASS._log(
self, level, msg, args, exc_info=exc_info, extra=extra
)
# pylint: disable=C0103
# pylint: disable=W0221
def makeRecord(self, name, level, fn, lno, msg, args, exc_info,
func=None, extra=None, sinfo=None):
# Let's remove exc_info_on_loglevel from extra
exc_info_on_loglevel = extra.pop('exc_info_on_loglevel')
jid = extra.pop('jid', '')
if jid:
log_fmt_jid = extra.pop('log_fmt_jid')
jid = log_fmt_jid % {'jid': jid}
if not extra:
# If nothing else is in extra, make it None
extra = None
# Let's try to make every logging message unicode
salt_system_encoding = __salt_system_encoding__
if salt_system_encoding == 'ascii':
# Encoding detection most likely failed, let's use the utf-8
# value which we defaulted before __salt_system_encoding__ was
# implemented
salt_system_encoding = 'utf-8'
if isinstance(msg, six.string_types) \
and not isinstance(msg, six.text_type):
try:
_msg = msg.decode(salt_system_encoding, 'replace')
except UnicodeDecodeError:
_msg = msg.decode(salt_system_encoding, 'ignore')
else:
_msg = msg
_args = []
for item in args:
if isinstance(item, six.string_types) \
and not isinstance(item, six.text_type):
try:
_args.append(item.decode(salt_system_encoding, 'replace'))
except UnicodeDecodeError:
_args.append(item.decode(salt_system_encoding, 'ignore'))
else:
_args.append(item)
_args = tuple(_args)
if six.PY3:
logrecord = _LOG_RECORD_FACTORY(name, level, fn, lno, _msg, _args,
exc_info, func, sinfo)
else:
logrecord = _LOG_RECORD_FACTORY(name, level, fn, lno, _msg, _args,
exc_info, func)
if extra is not None:
for key in extra:
if (key in ['message', 'asctime']) or (key in logrecord.__dict__):
raise KeyError(
'Attempt to overwrite \'{0}\' in LogRecord'.format(key)
)
logrecord.__dict__[key] = extra[key]
if exc_info_on_loglevel is not None:
# Let's add some custom attributes to the LogRecord class in order
# to include the exc_info on a per handler basis. This will allow
# showing tracebacks on logfiles but not on console if the logfile
# handler is enabled for the log level "exc_info_on_loglevel" and
# console handler is not.
logrecord.exc_info_on_loglevel_instance = sys.exc_info()
logrecord.exc_info_on_loglevel_formatted = None
logrecord.exc_info_on_loglevel = exc_info_on_loglevel
logrecord.jid = jid
return logrecord
# pylint: enable=C0103
# Override the python's logging logger class as soon as this module is imported
if logging.getLoggerClass() is not SaltLoggingClass:
logging.setLoggerClass(SaltLoggingClass)
logging.addLevelName(QUIET, 'QUIET')
logging.addLevelName(PROFILE, 'PROFILE')
logging.addLevelName(TRACE, 'TRACE')
logging.addLevelName(GARBAGE, 'GARBAGE')
if not logging.root.handlers:
# No configuration to the logging system has been done so far.
# Set the root logger at the lowest level possible
logging.root.setLevel(GARBAGE)
# Add a Null logging handler until logging is configured(will be
# removed at a later stage) so we stop getting:
# No handlers could be found for logger 'foo'
logging.root.addHandler(LOGGING_NULL_HANDLER)
# Add the queue logging handler so we can later sync all message records
# with the additional logging handlers
logging.root.addHandler(LOGGING_STORE_HANDLER)
def getLogger(name): # pylint: disable=C0103
'''
This function is just a helper, an alias to:
logging.getLogger(name)
Although you might find it useful, there's no reason why you should not be
using the aliased method.
'''
return logging.getLogger(name)
def setup_temp_logger(log_level='error'):
'''
Setup the temporary console logger
'''
if is_temp_logging_configured():
logging.getLogger(__name__).warning(
'Temporary logging is already configured'
)
return
if log_level is None:
log_level = 'warning'
level = LOG_LEVELS.get(log_level.lower(), logging.ERROR)
handler = None
for handler in logging.root.handlers:
if handler in (LOGGING_NULL_HANDLER, LOGGING_STORE_HANDLER):
continue
if not hasattr(handler, 'stream'):
# Not a stream handler, continue
continue
if handler.stream is sys.stderr:
# There's already a logging handler outputting to sys.stderr
break
else:
handler = LOGGING_TEMP_HANDLER
handler.setLevel(level)
# Set the default temporary console formatter config
formatter = logging.Formatter(
'[%(levelname)-8s] %(message)s', datefmt='%H:%M:%S'
)
handler.setFormatter(formatter)
logging.root.addHandler(handler)
# Sync the null logging handler messages with the temporary handler
if LOGGING_NULL_HANDLER is not None:
LOGGING_NULL_HANDLER.sync_with_handlers([handler])
else:
logging.getLogger(__name__).debug(
'LOGGING_NULL_HANDLER is already None, can\'t sync messages '
'with it'
)
# Remove the temporary null logging handler
__remove_null_logging_handler()
global __TEMP_LOGGING_CONFIGURED
__TEMP_LOGGING_CONFIGURED = True
def setup_console_logger(log_level='error', log_format=None, date_format=None):
'''
Setup the console logger
'''
if is_console_configured():
logging.getLogger(__name__).warning('Console logging already configured')
return
# Remove the temporary logging handler
__remove_temp_logging_handler()
if log_level is None:
log_level = 'warning'
level = LOG_LEVELS.get(log_level.lower(), logging.ERROR)
setLogRecordFactory(SaltColorLogRecord)
handler = None
for handler in logging.root.handlers:
if handler is LOGGING_STORE_HANDLER:
continue
if not hasattr(handler, 'stream'):
# Not a stream handler, continue
continue
if handler.stream is sys.stderr:
# There's already a logging handler outputting to sys.stderr
break
else:
handler = StreamHandler(sys.stderr)
handler.setLevel(level)
# Set the default console formatter config
if not log_format:
log_format = '[%(levelname)-8s] %(message)s'
if not date_format:
date_format = '%H:%M:%S'
formatter = logging.Formatter(log_format, datefmt=date_format)
handler.setFormatter(formatter)
logging.root.addHandler(handler)
global __CONSOLE_CONFIGURED
global __LOGGING_CONSOLE_HANDLER
__CONSOLE_CONFIGURED = True
__LOGGING_CONSOLE_HANDLER = handler
def setup_logfile_logger(log_path, log_level='error', log_format=None,
date_format=None, max_bytes=0, backup_count=0):
'''
Setup the logfile logger
Since version 0.10.6 we support logging to syslog, some examples:
tcp://localhost:514/LOG_USER
tcp://localhost/LOG_DAEMON
udp://localhost:5145/LOG_KERN
udp://localhost
file:///dev/log
file:///dev/log/LOG_SYSLOG
file:///dev/log/LOG_DAEMON
The above examples are self explanatory, but:
<file|udp|tcp>://<host|socketpath>:<port-if-required>/<log-facility>
If you're thinking on doing remote logging you might also be thinking that
you could point salt's logging to the remote syslog. **Please Don't!**
An issue has been reported when doing this over TCP when the logged lines
get concatenated. See #3061.
The preferred way to do remote logging is setup a local syslog, point
salt's logging to the local syslog(unix socket is much faster) and then
have the local syslog forward the log messages to the remote syslog.
'''
if is_logfile_configured():
logging.getLogger(__name__).warning('Logfile logging already configured')
return
if log_path is None:
logging.getLogger(__name__).warning(
'log_path setting is set to `None`. Nothing else to do'
)
return
# Remove the temporary logging handler
__remove_temp_logging_handler()
if log_level is None:
log_level = 'warning'
level = LOG_LEVELS.get(log_level.lower(), logging.ERROR)
parsed_log_path = urlparse(log_path)
root_logger = logging.getLogger()
if parsed_log_path.scheme in ('tcp', 'udp', 'file'):
syslog_opts = {
'facility': SysLogHandler.LOG_USER,
'socktype': socket.SOCK_DGRAM
}
if parsed_log_path.scheme == 'file' and parsed_log_path.path:
facility_name = parsed_log_path.path.split(os.sep)[-1].upper()
if not facility_name.startswith('LOG_'):
# The user is not specifying a syslog facility
facility_name = 'LOG_USER' # Syslog default
syslog_opts['address'] = parsed_log_path.path
else:
# The user has set a syslog facility, let's update the path to
# the logging socket
syslog_opts['address'] = os.sep.join(
parsed_log_path.path.split(os.sep)[:-1]
)
elif parsed_log_path.path:
# In case of udp or tcp with a facility specified
facility_name = parsed_log_path.path.lstrip(os.sep).upper()
if not facility_name.startswith('LOG_'):
# Logging facilities start with LOG_ if this is not the case
# fail right now!
raise RuntimeError(
'The syslog facility \'{0}\' is not known'.format(
facility_name
)
)
else:
# This is the case of udp or tcp without a facility specified
facility_name = 'LOG_USER' # Syslog default
facility = getattr(
SysLogHandler, facility_name, None
)
if facility is None:
# This python syslog version does not know about the user provided
# facility name
raise RuntimeError(
'The syslog facility \'{0}\' is not known'.format(
facility_name
)
)
syslog_opts['facility'] = facility
if parsed_log_path.scheme == 'tcp':
# tcp syslog support was only added on python versions >= 2.7
if sys.version_info < (2, 7):
raise RuntimeError(
'Python versions lower than 2.7 do not support logging '
'to syslog using tcp sockets'
)
syslog_opts['socktype'] = socket.SOCK_STREAM
if parsed_log_path.scheme in ('tcp', 'udp'):
syslog_opts['address'] = (
parsed_log_path.hostname,
parsed_log_path.port or logging.handlers.SYSLOG_UDP_PORT
)
if sys.version_info < (2, 7) or parsed_log_path.scheme == 'file':
# There's not socktype support on python versions lower than 2.7
syslog_opts.pop('socktype', None)
try:
# Et voilá! Finally our syslog handler instance
handler = SysLogHandler(**syslog_opts)
except socket.error as err:
logging.getLogger(__name__).error(
'Failed to setup the Syslog logging handler: %s', err
)
shutdown_multiprocessing_logging_listener()
sys.exit(2)
else:
# make sure, the logging directory exists and attempt to create it if necessary
log_dir = os.path.dirname(log_path)
if not os.path.exists(log_dir):
logging.getLogger(__name__).info(
'Log directory not found, trying to create it: %s', log_dir
)
try:
os.makedirs(log_dir, mode=0o700)
except OSError as ose:
logging.getLogger(__name__).warning(
'Failed to create directory for log file: %s (%s)', log_dir, ose
)
return
try:
# Logfile logging is UTF-8 on purpose.
# Since salt uses YAML and YAML uses either UTF-8 or UTF-16, if a
# user is not using plain ASCII, their system should be ready to
# handle UTF-8.
if max_bytes > 0:
handler = RotatingFileHandler(log_path,
mode='a',
maxBytes=max_bytes,
backupCount=backup_count,
encoding='utf-8',
delay=0)
else:
handler = WatchedFileHandler(log_path, mode='a', encoding='utf-8', delay=0)
except (IOError, OSError):
logging.getLogger(__name__).warning(
'Failed to open log file, do you have permission to write to %s?', log_path
)
# Do not proceed with any more configuration since it will fail, we
# have the console logging already setup and the user should see
# the error.
return
handler.setLevel(level)
# Set the default console formatter config
if not log_format:
log_format = '%(asctime)s [%(name)-15s][%(levelname)-8s] %(message)s'
if not date_format:
date_format = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter(log_format, datefmt=date_format)
handler.setFormatter(formatter)
root_logger.addHandler(handler)
global __LOGFILE_CONFIGURED
global __LOGGING_LOGFILE_HANDLER
__LOGFILE_CONFIGURED = True
__LOGGING_LOGFILE_HANDLER = handler
def setup_extended_logging(opts):
'''
Setup any additional logging handlers, internal or external
'''
if is_extended_logging_configured() is True:
# Don't re-configure external loggers
return
# Explicit late import of salt's loader
import salt.loader
# Let's keep a reference to the current logging handlers
initial_handlers = logging.root.handlers[:]
# Load any additional logging handlers
providers = salt.loader.log_handlers(opts)
# Let's keep track of the new logging handlers so we can sync the stored
# log records with them
additional_handlers = []
for name, get_handlers_func in six.iteritems(providers):
logging.getLogger(__name__).info('Processing `log_handlers.%s`', name)
# Keep a reference to the logging handlers count before getting the
# possible additional ones.
initial_handlers_count = len(logging.root.handlers)
handlers = get_handlers_func()
if isinstance(handlers, types.GeneratorType):
handlers = list(handlers)
elif handlers is False or handlers == [False]:
# A false return value means not configuring any logging handler on
# purpose
logging.getLogger(__name__).info(
'The `log_handlers.%s.setup_handlers()` function returned '
'`False` which means no logging handler was configured on '
'purpose. Continuing...', name
)
continue
else:
# Make sure we have an iterable
handlers = [handlers]
for handler in handlers:
if not handler and \
len(logging.root.handlers) == initial_handlers_count:
logging.getLogger(__name__).info(
'The `log_handlers.%s`, did not return any handlers '
'and the global handlers count did not increase. This '
'could be a sign of `log_handlers.%s` not working as '
'supposed', name, name
)
continue
logging.getLogger(__name__).debug(
'Adding the \'%s\' provided logging handler: \'%s\'',
name, handler
)
additional_handlers.append(handler)
logging.root.addHandler(handler)
for handler in logging.root.handlers:
if handler in initial_handlers:
continue
additional_handlers.append(handler)
# Sync the null logging handler messages with the temporary handler
if LOGGING_STORE_HANDLER is not None:
LOGGING_STORE_HANDLER.sync_with_handlers(additional_handlers)
else:
logging.getLogger(__name__).debug(
'LOGGING_STORE_HANDLER is already None, can\'t sync messages '
'with it'
)
# Remove the temporary queue logging handler
__remove_queue_logging_handler()
# Remove the temporary null logging handler (if it exists)
__remove_null_logging_handler()
global __EXTERNAL_LOGGERS_CONFIGURED
__EXTERNAL_LOGGERS_CONFIGURED = True
def get_multiprocessing_logging_queue():
global __MP_LOGGING_QUEUE
if __MP_IN_MAINPROCESS is False:
# We're not in the MainProcess, return! No Queue shall be instantiated
return __MP_LOGGING_QUEUE
if __MP_LOGGING_QUEUE is None:
__MP_LOGGING_QUEUE = multiprocessing.Queue()
return __MP_LOGGING_QUEUE
def set_multiprocessing_logging_queue(queue):
global __MP_LOGGING_QUEUE
if __MP_LOGGING_QUEUE is not queue:
__MP_LOGGING_QUEUE = queue
def get_multiprocessing_logging_level():
return __MP_LOGGING_LEVEL
def set_multiprocessing_logging_level(log_level):
global __MP_LOGGING_LEVEL
__MP_LOGGING_LEVEL = log_level
def set_multiprocessing_logging_level_by_opts(opts):
'''
This will set the multiprocessing logging level to the lowest
logging level of all the types of logging that are configured.
'''
global __MP_LOGGING_LEVEL
log_levels = [
LOG_LEVELS.get(opts.get('log_level', '').lower(), logging.ERROR),
LOG_LEVELS.get(opts.get('log_level_logfile', '').lower(), logging.ERROR)
]
for level in six.itervalues(opts.get('log_granular_levels', {})):
log_levels.append(
LOG_LEVELS.get(level.lower(), logging.ERROR)
)
__MP_LOGGING_LEVEL = min(log_levels)
def setup_multiprocessing_logging_listener(opts, queue=None):
global __MP_LOGGING_QUEUE_PROCESS
global __MP_LOGGING_LISTENER_CONFIGURED
global __MP_MAINPROCESS_ID
if __MP_IN_MAINPROCESS is False:
# We're not in the MainProcess, return! No logging listener setup shall happen
return
if __MP_LOGGING_LISTENER_CONFIGURED is True:
return
if __MP_MAINPROCESS_ID is not None and __MP_MAINPROCESS_ID != os.getpid():
# We're not in the MainProcess, return! No logging listener setup shall happen
return
__MP_MAINPROCESS_ID = os.getpid()
__MP_LOGGING_QUEUE_PROCESS = multiprocessing.Process(
target=__process_multiprocessing_logging_queue,
args=(opts, queue or get_multiprocessing_logging_queue(),)
)
__MP_LOGGING_QUEUE_PROCESS.daemon = True
__MP_LOGGING_QUEUE_PROCESS.start()
__MP_LOGGING_LISTENER_CONFIGURED = True
def setup_multiprocessing_logging(queue=None):
'''
This code should be called from within a running multiprocessing
process instance.
'''
from salt.utils.platform import is_windows
global __MP_LOGGING_CONFIGURED
global __MP_LOGGING_QUEUE_HANDLER
if __MP_IN_MAINPROCESS is True and not is_windows():
# We're in the MainProcess, return! No multiprocessing logging setup shall happen
# Windows is the exception where we want to set up multiprocessing
# logging in the MainProcess.
return
try:
logging._acquireLock() # pylint: disable=protected-access
if __MP_LOGGING_CONFIGURED is True:
return
# Let's set it to true as fast as possible
__MP_LOGGING_CONFIGURED = True
if __MP_LOGGING_QUEUE_HANDLER is not None:
return
# The temp null and temp queue logging handlers will store messages.
# Since noone will process them, memory usage will grow. If they
# exist, remove them.
__remove_null_logging_handler()
__remove_queue_logging_handler()
# Let's add a queue handler to the logging root handlers
__MP_LOGGING_QUEUE_HANDLER = SaltLogQueueHandler(queue or get_multiprocessing_logging_queue())
logging.root.addHandler(__MP_LOGGING_QUEUE_HANDLER)
# Set the logging root level to the lowest needed level to get all
# desired messages.
log_level = get_multiprocessing_logging_level()
logging.root.setLevel(log_level)
logging.getLogger(__name__).debug(
'Multiprocessing queue logging configured for the process running '
'under PID: %s at log level %s', os.getpid(), log_level
)
# The above logging call will create, in some situations, a futex wait
# lock condition, probably due to the multiprocessing Queue's internal
# lock and semaphore mechanisms.
# A small sleep will allow us not to hit that futex wait lock condition.
time.sleep(0.0001)
finally:
logging._releaseLock() # pylint: disable=protected-access
def shutdown_console_logging():
global __CONSOLE_CONFIGURED
global __LOGGING_CONSOLE_HANDLER
if not __CONSOLE_CONFIGURED or not __LOGGING_CONSOLE_HANDLER:
return
try:
logging._acquireLock()
logging.root.removeHandler(__LOGGING_CONSOLE_HANDLER)
__LOGGING_CONSOLE_HANDLER = None
__CONSOLE_CONFIGURED = False
finally:
logging._releaseLock()
def shutdown_logfile_logging():
global __LOGFILE_CONFIGURED
global __LOGGING_LOGFILE_HANDLER
if not __LOGFILE_CONFIGURED or not __LOGGING_LOGFILE_HANDLER:
return
try:
logging._acquireLock()
logging.root.removeHandler(__LOGGING_LOGFILE_HANDLER)
__LOGGING_LOGFILE_HANDLER = None
__LOGFILE_CONFIGURED = False
finally:
logging._releaseLock()
def shutdown_temp_logging():
__remove_temp_logging_handler()
def shutdown_multiprocessing_logging():
global __MP_LOGGING_CONFIGURED
global __MP_LOGGING_QUEUE_HANDLER
if not __MP_LOGGING_CONFIGURED or not __MP_LOGGING_QUEUE_HANDLER:
return
try:
logging._acquireLock()
# Let's remove the queue handler from the logging root handlers
logging.root.removeHandler(__MP_LOGGING_QUEUE_HANDLER)
__MP_LOGGING_QUEUE_HANDLER = None
__MP_LOGGING_CONFIGURED = False
if not logging.root.handlers:
# Ensure we have at least one logging root handler so
# something can handle logging messages. This case should
# only occur on Windows since on Windows we log to console
# and file through the Multiprocessing Logging Listener.
setup_console_logger()
finally:
logging._releaseLock()
def shutdown_multiprocessing_logging_listener(daemonizing=False):
global __MP_LOGGING_QUEUE
global __MP_LOGGING_QUEUE_PROCESS
global __MP_LOGGING_LISTENER_CONFIGURED
if daemonizing is False and __MP_IN_MAINPROCESS is True:
# We're in the MainProcess and we're not daemonizing, return!
# No multiprocessing logging listener shutdown shall happen
return
if not daemonizing:
# Need to remove the queue handler so that it doesn't try to send
# data over a queue that was shut down on the listener end.
shutdown_multiprocessing_logging()
if __MP_LOGGING_QUEUE_PROCESS is None:
return
if __MP_MAINPROCESS_ID is not None and __MP_MAINPROCESS_ID != os.getpid():
# We're not in the MainProcess, return! No logging listener setup shall happen
return
if __MP_LOGGING_QUEUE_PROCESS.is_alive():
logging.getLogger(__name__).debug('Stopping the multiprocessing logging queue listener')
try:
# Sent None sentinel to stop the logging processing queue
__MP_LOGGING_QUEUE.put(None)
# Let's join the multiprocessing logging handle thread
time.sleep(0.5)
logging.getLogger(__name__).debug('closing multiprocessing queue')
__MP_LOGGING_QUEUE.close()
logging.getLogger(__name__).debug('joining multiprocessing queue thread')
__MP_LOGGING_QUEUE.join_thread()
__MP_LOGGING_QUEUE = None
__MP_LOGGING_QUEUE_PROCESS.join(1)
__MP_LOGGING_QUEUE = None
except IOError:
# We were unable to deliver the sentinel to the queue
# carry on...
pass
if __MP_LOGGING_QUEUE_PROCESS.is_alive():
# Process is still alive!?
__MP_LOGGING_QUEUE_PROCESS.terminate()
__MP_LOGGING_QUEUE_PROCESS = None
__MP_LOGGING_LISTENER_CONFIGURED = False
logging.getLogger(__name__).debug('Stopped the multiprocessing logging queue listener')
def set_logger_level(logger_name, log_level='error'):
'''
Tweak a specific logger's logging level
'''
logging.getLogger(logger_name).setLevel(
LOG_LEVELS.get(log_level.lower(), logging.ERROR)
)
def patch_python_logging_handlers():
'''
Patch the python logging handlers with out mixed-in classes
'''
logging.StreamHandler = StreamHandler
logging.FileHandler = FileHandler
logging.handlers.SysLogHandler = SysLogHandler
logging.handlers.WatchedFileHandler = WatchedFileHandler
logging.handlers.RotatingFileHandler = RotatingFileHandler
if sys.version_info >= (3, 2):
logging.handlers.QueueHandler = QueueHandler
def __process_multiprocessing_logging_queue(opts, queue):
# Avoid circular import
import salt.utils.process
salt.utils.process.appendproctitle('MultiprocessingLoggingQueue')
# Assign UID/GID of user to proc if set
from salt.utils.verify import check_user
user = opts.get('user')
if user:
check_user(user)
from salt.utils.platform import is_windows
if is_windows():
# On Windows, creating a new process doesn't fork (copy the parent
# process image). Due to this, we need to setup all of our logging
# inside this process.
setup_temp_logger()
setup_console_logger(
log_level=opts.get('log_level'),
log_format=opts.get('log_fmt_console'),
date_format=opts.get('log_datefmt_console')
)
setup_logfile_logger(
opts.get('log_file'),
log_level=opts.get('log_level_logfile'),
log_format=opts.get('log_fmt_logfile'),
date_format=opts.get('log_datefmt_logfile'),
max_bytes=opts.get('log_rotate_max_bytes', 0),
backup_count=opts.get('log_rotate_backup_count', 0)
)
setup_extended_logging(opts)
while True:
try:
record = queue.get()
if record is None:
# A sentinel to stop processing the queue
break
# Just log everything, filtering will happen on the main process
# logging handlers
logger = logging.getLogger(record.name)
logger.handle(record)
except (EOFError, KeyboardInterrupt, SystemExit):
break
except Exception as exc: # pylint: disable=broad-except
logging.getLogger(__name__).warning(
'An exception occurred in the multiprocessing logging '
'queue thread: %s', exc, exc_info_on_loglevel=logging.DEBUG
)
def __remove_null_logging_handler():
'''
This function will run once the temporary logging has been configured. It
just removes the NullHandler from the logging handlers.
'''
global LOGGING_NULL_HANDLER
if LOGGING_NULL_HANDLER is None:
# Already removed
return
root_logger = logging.getLogger()
for handler in root_logger.handlers:
if handler is LOGGING_NULL_HANDLER:
root_logger.removeHandler(LOGGING_NULL_HANDLER)
# Redefine the null handler to None so it can be garbage collected
LOGGING_NULL_HANDLER = None
break
def __remove_queue_logging_handler():
'''
This function will run once the additional loggers have been synchronized.
It just removes the QueueLoggingHandler from the logging handlers.
'''
global LOGGING_STORE_HANDLER
if LOGGING_STORE_HANDLER is None:
# Already removed
return
root_logger = logging.getLogger()
for handler in root_logger.handlers:
if handler is LOGGING_STORE_HANDLER:
root_logger.removeHandler(LOGGING_STORE_HANDLER)
# Redefine the null handler to None so it can be garbage collected
LOGGING_STORE_HANDLER = None
break
def __global_logging_exception_handler(exc_type, exc_value, exc_traceback):
'''
This function will log all un-handled python exceptions.
'''
if exc_type.__name__ == "KeyboardInterrupt":
# Do not log the exception or display the traceback on Keyboard Interrupt
# Stop the logging queue listener thread
if is_mp_logging_listener_configured():
shutdown_multiprocessing_logging_listener()
else:
# Log the exception
logging.getLogger(__name__).error(
'An un-handled exception was caught by salt\'s global exception '
'handler:\n%s: %s\n%s',
exc_type.__name__,
exc_value,
''.join(traceback.format_exception(
exc_type, exc_value, exc_traceback
)).strip()
)
# Call the original sys.excepthook
sys.__excepthook__(exc_type, exc_value, exc_traceback)
# Set our own exception handler as the one to use
sys.excepthook = __global_logging_exception_handler
|
saltstack/salt
|
salt/log/setup.py
|
__global_logging_exception_handler
|
python
|
def __global_logging_exception_handler(exc_type, exc_value, exc_traceback):
'''
This function will log all un-handled python exceptions.
'''
if exc_type.__name__ == "KeyboardInterrupt":
# Do not log the exception or display the traceback on Keyboard Interrupt
# Stop the logging queue listener thread
if is_mp_logging_listener_configured():
shutdown_multiprocessing_logging_listener()
else:
# Log the exception
logging.getLogger(__name__).error(
'An un-handled exception was caught by salt\'s global exception '
'handler:\n%s: %s\n%s',
exc_type.__name__,
exc_value,
''.join(traceback.format_exception(
exc_type, exc_value, exc_traceback
)).strip()
)
# Call the original sys.excepthook
sys.__excepthook__(exc_type, exc_value, exc_traceback)
|
This function will log all un-handled python exceptions.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/setup.py#L1200-L1221
| null |
# -*- coding: utf-8 -*-
'''
:codeauthor: Pedro Algarvio (pedro@algarvio.me)
salt.log.setup
~~~~~~~~~~~~~~
This is where Salt's logging gets set up.
This module should be imported as soon as possible, preferably the first
module salt or any salt depending library imports so any new logging
logger instance uses our ``salt.log.setup.SaltLoggingClass``.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import re
import sys
import time
import types
import socket
import logging
import logging.handlers
import traceback
import multiprocessing
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves.urllib.parse import urlparse # pylint: disable=import-error,no-name-in-module
# Let's define these custom logging levels before importing the salt.log.mixins
# since they will be used there
PROFILE = logging.PROFILE = 15
TRACE = logging.TRACE = 5
GARBAGE = logging.GARBAGE = 1
QUIET = logging.QUIET = 1000
# Import salt libs
from salt.textformat import TextFormat
from salt.log.handlers import (TemporaryLoggingHandler,
StreamHandler,
SysLogHandler,
FileHandler,
WatchedFileHandler,
RotatingFileHandler,
QueueHandler)
from salt.log.mixins import LoggingMixInMeta, NewStyleClassMixIn
from salt.utils.ctx import RequestContext
LOG_LEVELS = {
'all': logging.NOTSET,
'debug': logging.DEBUG,
'error': logging.ERROR,
'critical': logging.CRITICAL,
'garbage': GARBAGE,
'info': logging.INFO,
'profile': PROFILE,
'quiet': QUIET,
'trace': TRACE,
'warning': logging.WARNING,
}
LOG_VALUES_TO_LEVELS = dict((v, k) for (k, v) in LOG_LEVELS.items())
LOG_COLORS = {
'levels': {
'QUIET': TextFormat('reset'),
'CRITICAL': TextFormat('bold', 'red'),
'ERROR': TextFormat('bold', 'red'),
'WARNING': TextFormat('bold', 'yellow'),
'INFO': TextFormat('bold', 'green'),
'PROFILE': TextFormat('bold', 'cyan'),
'DEBUG': TextFormat('bold', 'cyan'),
'TRACE': TextFormat('bold', 'magenta'),
'GARBAGE': TextFormat('bold', 'blue'),
'NOTSET': TextFormat('reset'),
'SUBDEBUG': TextFormat('bold', 'cyan'), # used by multiprocessing.log_to_stderr()
'SUBWARNING': TextFormat('bold', 'yellow'), # used by multiprocessing.log_to_stderr()
},
'msgs': {
'QUIET': TextFormat('reset'),
'CRITICAL': TextFormat('bold', 'red'),
'ERROR': TextFormat('red'),
'WARNING': TextFormat('yellow'),
'INFO': TextFormat('green'),
'PROFILE': TextFormat('bold', 'cyan'),
'DEBUG': TextFormat('cyan'),
'TRACE': TextFormat('magenta'),
'GARBAGE': TextFormat('blue'),
'NOTSET': TextFormat('reset'),
'SUBDEBUG': TextFormat('bold', 'cyan'), # used by multiprocessing.log_to_stderr()
'SUBWARNING': TextFormat('bold', 'yellow'), # used by multiprocessing.log_to_stderr()
},
'name': TextFormat('bold', 'green'),
'process': TextFormat('bold', 'blue'),
}
# Make a list of log level names sorted by log level
SORTED_LEVEL_NAMES = [
l[0] for l in sorted(six.iteritems(LOG_LEVELS), key=lambda x: x[1])
]
# Store an instance of the current logging logger class
LOGGING_LOGGER_CLASS = logging.getLoggerClass()
MODNAME_PATTERN = re.compile(r'(?P<name>%%\(name\)(?:\-(?P<digits>[\d]+))?s)')
__CONSOLE_CONFIGURED = False
__LOGGING_CONSOLE_HANDLER = None
__LOGFILE_CONFIGURED = False
__LOGGING_LOGFILE_HANDLER = None
__TEMP_LOGGING_CONFIGURED = False
__EXTERNAL_LOGGERS_CONFIGURED = False
__MP_LOGGING_LISTENER_CONFIGURED = False
__MP_LOGGING_CONFIGURED = False
__MP_LOGGING_QUEUE = None
__MP_LOGGING_LEVEL = GARBAGE
__MP_LOGGING_QUEUE_PROCESS = None
__MP_LOGGING_QUEUE_HANDLER = None
__MP_IN_MAINPROCESS = multiprocessing.current_process().name == 'MainProcess'
__MP_MAINPROCESS_ID = None
class __NullLoggingHandler(TemporaryLoggingHandler):
'''
This class exists just to better identify which temporary logging
handler is being used for what.
'''
class __StoreLoggingHandler(TemporaryLoggingHandler):
'''
This class exists just to better identify which temporary logging
handler is being used for what.
'''
def is_console_configured():
return __CONSOLE_CONFIGURED
def is_logfile_configured():
return __LOGFILE_CONFIGURED
def is_logging_configured():
return __CONSOLE_CONFIGURED or __LOGFILE_CONFIGURED
def is_temp_logging_configured():
return __TEMP_LOGGING_CONFIGURED
def is_mp_logging_listener_configured():
return __MP_LOGGING_LISTENER_CONFIGURED
def is_mp_logging_configured():
return __MP_LOGGING_LISTENER_CONFIGURED
def is_extended_logging_configured():
return __EXTERNAL_LOGGERS_CONFIGURED
# Store a reference to the temporary queue logging handler
LOGGING_NULL_HANDLER = __NullLoggingHandler(logging.WARNING)
# Store a reference to the temporary console logger
LOGGING_TEMP_HANDLER = StreamHandler(sys.stderr)
# Store a reference to the "storing" logging handler
LOGGING_STORE_HANDLER = __StoreLoggingHandler()
class SaltLogQueueHandler(QueueHandler):
pass
class SaltLogRecord(logging.LogRecord):
def __init__(self, *args, **kwargs):
logging.LogRecord.__init__(self, *args, **kwargs)
# pylint: disable=E1321
self.bracketname = '[%-17s]' % self.name
self.bracketlevel = '[%-8s]' % self.levelname
self.bracketprocess = '[%5s]' % self.process
# pylint: enable=E1321
class SaltColorLogRecord(SaltLogRecord):
def __init__(self, *args, **kwargs):
SaltLogRecord.__init__(self, *args, **kwargs)
reset = TextFormat('reset')
clevel = LOG_COLORS['levels'].get(self.levelname, reset)
cmsg = LOG_COLORS['msgs'].get(self.levelname, reset)
# pylint: disable=E1321
self.colorname = '%s[%-17s]%s' % (LOG_COLORS['name'],
self.name,
reset)
self.colorlevel = '%s[%-8s]%s' % (clevel,
self.levelname,
reset)
self.colorprocess = '%s[%5s]%s' % (LOG_COLORS['process'],
self.process,
reset)
self.colormsg = '%s%s%s' % (cmsg, self.getMessage(), reset)
# pylint: enable=E1321
_LOG_RECORD_FACTORY = SaltLogRecord
def setLogRecordFactory(factory):
'''
Set the factory to be used when instantiating a log record.
:param factory: A callable which will be called to instantiate
a log record.
'''
global _LOG_RECORD_FACTORY
_LOG_RECORD_FACTORY = factory
def getLogRecordFactory():
'''
Return the factory to be used when instantiating a log record.
'''
return _LOG_RECORD_FACTORY
setLogRecordFactory(SaltLogRecord)
class SaltLoggingClass(six.with_metaclass(LoggingMixInMeta, LOGGING_LOGGER_CLASS, NewStyleClassMixIn)):
def __new__(cls, *args): # pylint: disable=W0613,E0012
'''
We override `__new__` in our logging logger class in order to provide
some additional features like expand the module name padding if length
is being used, and also some Unicode fixes.
This code overhead will only be executed when the class is
instantiated, i.e.:
logging.getLogger(__name__)
'''
instance = super(SaltLoggingClass, cls).__new__(cls)
try:
max_logger_length = len(max(
list(logging.Logger.manager.loggerDict), key=len
))
for handler in logging.root.handlers:
if handler in (LOGGING_NULL_HANDLER,
LOGGING_STORE_HANDLER,
LOGGING_TEMP_HANDLER):
continue
formatter = handler.formatter
if not formatter:
continue
if not handler.lock:
handler.createLock()
handler.acquire()
fmt = formatter._fmt.replace('%', '%%')
match = MODNAME_PATTERN.search(fmt)
if not match:
# Not matched. Release handler and return.
handler.release()
return instance
if 'digits' not in match.groupdict():
# No digits group. Release handler and return.
handler.release()
return instance
digits = match.group('digits')
if not digits or not (digits and digits.isdigit()):
# No valid digits. Release handler and return.
handler.release()
return instance
if int(digits) < max_logger_length:
# Formatter digits value is lower than current max, update.
fmt = fmt.replace(match.group('name'), '%%(name)-%ds')
formatter = logging.Formatter(
fmt % max_logger_length,
datefmt=formatter.datefmt
)
handler.setFormatter(formatter)
handler.release()
except ValueError:
# There are no registered loggers yet
pass
return instance
def _log(self, level, msg, args, exc_info=None, extra=None, # pylint: disable=arguments-differ
exc_info_on_loglevel=None):
# If both exc_info and exc_info_on_loglevel are both passed, let's fail
if extra is None:
extra = {}
current_jid = RequestContext.current.get('data', {}).get('jid', None)
log_fmt_jid = RequestContext.current.get('opts', {}).get('log_fmt_jid', None)
if current_jid is not None:
extra['jid'] = current_jid
if log_fmt_jid is not None:
extra['log_fmt_jid'] = log_fmt_jid
if exc_info and exc_info_on_loglevel:
raise RuntimeError(
'Only one of \'exc_info\' and \'exc_info_on_loglevel\' is '
'permitted'
)
if exc_info_on_loglevel is not None:
if isinstance(exc_info_on_loglevel, six.string_types):
exc_info_on_loglevel = LOG_LEVELS.get(exc_info_on_loglevel,
logging.ERROR)
elif not isinstance(exc_info_on_loglevel, int):
raise RuntimeError(
'The value of \'exc_info_on_loglevel\' needs to be a '
'logging level or a logging level name, not \'{0}\''
.format(exc_info_on_loglevel)
)
if extra is None:
extra = {'exc_info_on_loglevel': exc_info_on_loglevel}
else:
extra['exc_info_on_loglevel'] = exc_info_on_loglevel
LOGGING_LOGGER_CLASS._log(
self, level, msg, args, exc_info=exc_info, extra=extra
)
# pylint: disable=C0103
# pylint: disable=W0221
def makeRecord(self, name, level, fn, lno, msg, args, exc_info,
func=None, extra=None, sinfo=None):
# Let's remove exc_info_on_loglevel from extra
exc_info_on_loglevel = extra.pop('exc_info_on_loglevel')
jid = extra.pop('jid', '')
if jid:
log_fmt_jid = extra.pop('log_fmt_jid')
jid = log_fmt_jid % {'jid': jid}
if not extra:
# If nothing else is in extra, make it None
extra = None
# Let's try to make every logging message unicode
salt_system_encoding = __salt_system_encoding__
if salt_system_encoding == 'ascii':
# Encoding detection most likely failed, let's use the utf-8
# value which we defaulted before __salt_system_encoding__ was
# implemented
salt_system_encoding = 'utf-8'
if isinstance(msg, six.string_types) \
and not isinstance(msg, six.text_type):
try:
_msg = msg.decode(salt_system_encoding, 'replace')
except UnicodeDecodeError:
_msg = msg.decode(salt_system_encoding, 'ignore')
else:
_msg = msg
_args = []
for item in args:
if isinstance(item, six.string_types) \
and not isinstance(item, six.text_type):
try:
_args.append(item.decode(salt_system_encoding, 'replace'))
except UnicodeDecodeError:
_args.append(item.decode(salt_system_encoding, 'ignore'))
else:
_args.append(item)
_args = tuple(_args)
if six.PY3:
logrecord = _LOG_RECORD_FACTORY(name, level, fn, lno, _msg, _args,
exc_info, func, sinfo)
else:
logrecord = _LOG_RECORD_FACTORY(name, level, fn, lno, _msg, _args,
exc_info, func)
if extra is not None:
for key in extra:
if (key in ['message', 'asctime']) or (key in logrecord.__dict__):
raise KeyError(
'Attempt to overwrite \'{0}\' in LogRecord'.format(key)
)
logrecord.__dict__[key] = extra[key]
if exc_info_on_loglevel is not None:
# Let's add some custom attributes to the LogRecord class in order
# to include the exc_info on a per handler basis. This will allow
# showing tracebacks on logfiles but not on console if the logfile
# handler is enabled for the log level "exc_info_on_loglevel" and
# console handler is not.
logrecord.exc_info_on_loglevel_instance = sys.exc_info()
logrecord.exc_info_on_loglevel_formatted = None
logrecord.exc_info_on_loglevel = exc_info_on_loglevel
logrecord.jid = jid
return logrecord
# pylint: enable=C0103
# Override the python's logging logger class as soon as this module is imported
if logging.getLoggerClass() is not SaltLoggingClass:
logging.setLoggerClass(SaltLoggingClass)
logging.addLevelName(QUIET, 'QUIET')
logging.addLevelName(PROFILE, 'PROFILE')
logging.addLevelName(TRACE, 'TRACE')
logging.addLevelName(GARBAGE, 'GARBAGE')
if not logging.root.handlers:
# No configuration to the logging system has been done so far.
# Set the root logger at the lowest level possible
logging.root.setLevel(GARBAGE)
# Add a Null logging handler until logging is configured(will be
# removed at a later stage) so we stop getting:
# No handlers could be found for logger 'foo'
logging.root.addHandler(LOGGING_NULL_HANDLER)
# Add the queue logging handler so we can later sync all message records
# with the additional logging handlers
logging.root.addHandler(LOGGING_STORE_HANDLER)
def getLogger(name): # pylint: disable=C0103
'''
This function is just a helper, an alias to:
logging.getLogger(name)
Although you might find it useful, there's no reason why you should not be
using the aliased method.
'''
return logging.getLogger(name)
def setup_temp_logger(log_level='error'):
'''
Setup the temporary console logger
'''
if is_temp_logging_configured():
logging.getLogger(__name__).warning(
'Temporary logging is already configured'
)
return
if log_level is None:
log_level = 'warning'
level = LOG_LEVELS.get(log_level.lower(), logging.ERROR)
handler = None
for handler in logging.root.handlers:
if handler in (LOGGING_NULL_HANDLER, LOGGING_STORE_HANDLER):
continue
if not hasattr(handler, 'stream'):
# Not a stream handler, continue
continue
if handler.stream is sys.stderr:
# There's already a logging handler outputting to sys.stderr
break
else:
handler = LOGGING_TEMP_HANDLER
handler.setLevel(level)
# Set the default temporary console formatter config
formatter = logging.Formatter(
'[%(levelname)-8s] %(message)s', datefmt='%H:%M:%S'
)
handler.setFormatter(formatter)
logging.root.addHandler(handler)
# Sync the null logging handler messages with the temporary handler
if LOGGING_NULL_HANDLER is not None:
LOGGING_NULL_HANDLER.sync_with_handlers([handler])
else:
logging.getLogger(__name__).debug(
'LOGGING_NULL_HANDLER is already None, can\'t sync messages '
'with it'
)
# Remove the temporary null logging handler
__remove_null_logging_handler()
global __TEMP_LOGGING_CONFIGURED
__TEMP_LOGGING_CONFIGURED = True
def setup_console_logger(log_level='error', log_format=None, date_format=None):
'''
Setup the console logger
'''
if is_console_configured():
logging.getLogger(__name__).warning('Console logging already configured')
return
# Remove the temporary logging handler
__remove_temp_logging_handler()
if log_level is None:
log_level = 'warning'
level = LOG_LEVELS.get(log_level.lower(), logging.ERROR)
setLogRecordFactory(SaltColorLogRecord)
handler = None
for handler in logging.root.handlers:
if handler is LOGGING_STORE_HANDLER:
continue
if not hasattr(handler, 'stream'):
# Not a stream handler, continue
continue
if handler.stream is sys.stderr:
# There's already a logging handler outputting to sys.stderr
break
else:
handler = StreamHandler(sys.stderr)
handler.setLevel(level)
# Set the default console formatter config
if not log_format:
log_format = '[%(levelname)-8s] %(message)s'
if not date_format:
date_format = '%H:%M:%S'
formatter = logging.Formatter(log_format, datefmt=date_format)
handler.setFormatter(formatter)
logging.root.addHandler(handler)
global __CONSOLE_CONFIGURED
global __LOGGING_CONSOLE_HANDLER
__CONSOLE_CONFIGURED = True
__LOGGING_CONSOLE_HANDLER = handler
def setup_logfile_logger(log_path, log_level='error', log_format=None,
date_format=None, max_bytes=0, backup_count=0):
'''
Setup the logfile logger
Since version 0.10.6 we support logging to syslog, some examples:
tcp://localhost:514/LOG_USER
tcp://localhost/LOG_DAEMON
udp://localhost:5145/LOG_KERN
udp://localhost
file:///dev/log
file:///dev/log/LOG_SYSLOG
file:///dev/log/LOG_DAEMON
The above examples are self explanatory, but:
<file|udp|tcp>://<host|socketpath>:<port-if-required>/<log-facility>
If you're thinking on doing remote logging you might also be thinking that
you could point salt's logging to the remote syslog. **Please Don't!**
An issue has been reported when doing this over TCP when the logged lines
get concatenated. See #3061.
The preferred way to do remote logging is setup a local syslog, point
salt's logging to the local syslog(unix socket is much faster) and then
have the local syslog forward the log messages to the remote syslog.
'''
if is_logfile_configured():
logging.getLogger(__name__).warning('Logfile logging already configured')
return
if log_path is None:
logging.getLogger(__name__).warning(
'log_path setting is set to `None`. Nothing else to do'
)
return
# Remove the temporary logging handler
__remove_temp_logging_handler()
if log_level is None:
log_level = 'warning'
level = LOG_LEVELS.get(log_level.lower(), logging.ERROR)
parsed_log_path = urlparse(log_path)
root_logger = logging.getLogger()
if parsed_log_path.scheme in ('tcp', 'udp', 'file'):
syslog_opts = {
'facility': SysLogHandler.LOG_USER,
'socktype': socket.SOCK_DGRAM
}
if parsed_log_path.scheme == 'file' and parsed_log_path.path:
facility_name = parsed_log_path.path.split(os.sep)[-1].upper()
if not facility_name.startswith('LOG_'):
# The user is not specifying a syslog facility
facility_name = 'LOG_USER' # Syslog default
syslog_opts['address'] = parsed_log_path.path
else:
# The user has set a syslog facility, let's update the path to
# the logging socket
syslog_opts['address'] = os.sep.join(
parsed_log_path.path.split(os.sep)[:-1]
)
elif parsed_log_path.path:
# In case of udp or tcp with a facility specified
facility_name = parsed_log_path.path.lstrip(os.sep).upper()
if not facility_name.startswith('LOG_'):
# Logging facilities start with LOG_ if this is not the case
# fail right now!
raise RuntimeError(
'The syslog facility \'{0}\' is not known'.format(
facility_name
)
)
else:
# This is the case of udp or tcp without a facility specified
facility_name = 'LOG_USER' # Syslog default
facility = getattr(
SysLogHandler, facility_name, None
)
if facility is None:
# This python syslog version does not know about the user provided
# facility name
raise RuntimeError(
'The syslog facility \'{0}\' is not known'.format(
facility_name
)
)
syslog_opts['facility'] = facility
if parsed_log_path.scheme == 'tcp':
# tcp syslog support was only added on python versions >= 2.7
if sys.version_info < (2, 7):
raise RuntimeError(
'Python versions lower than 2.7 do not support logging '
'to syslog using tcp sockets'
)
syslog_opts['socktype'] = socket.SOCK_STREAM
if parsed_log_path.scheme in ('tcp', 'udp'):
syslog_opts['address'] = (
parsed_log_path.hostname,
parsed_log_path.port or logging.handlers.SYSLOG_UDP_PORT
)
if sys.version_info < (2, 7) or parsed_log_path.scheme == 'file':
# There's not socktype support on python versions lower than 2.7
syslog_opts.pop('socktype', None)
try:
# Et voilá! Finally our syslog handler instance
handler = SysLogHandler(**syslog_opts)
except socket.error as err:
logging.getLogger(__name__).error(
'Failed to setup the Syslog logging handler: %s', err
)
shutdown_multiprocessing_logging_listener()
sys.exit(2)
else:
# make sure, the logging directory exists and attempt to create it if necessary
log_dir = os.path.dirname(log_path)
if not os.path.exists(log_dir):
logging.getLogger(__name__).info(
'Log directory not found, trying to create it: %s', log_dir
)
try:
os.makedirs(log_dir, mode=0o700)
except OSError as ose:
logging.getLogger(__name__).warning(
'Failed to create directory for log file: %s (%s)', log_dir, ose
)
return
try:
# Logfile logging is UTF-8 on purpose.
# Since salt uses YAML and YAML uses either UTF-8 or UTF-16, if a
# user is not using plain ASCII, their system should be ready to
# handle UTF-8.
if max_bytes > 0:
handler = RotatingFileHandler(log_path,
mode='a',
maxBytes=max_bytes,
backupCount=backup_count,
encoding='utf-8',
delay=0)
else:
handler = WatchedFileHandler(log_path, mode='a', encoding='utf-8', delay=0)
except (IOError, OSError):
logging.getLogger(__name__).warning(
'Failed to open log file, do you have permission to write to %s?', log_path
)
# Do not proceed with any more configuration since it will fail, we
# have the console logging already setup and the user should see
# the error.
return
handler.setLevel(level)
# Set the default console formatter config
if not log_format:
log_format = '%(asctime)s [%(name)-15s][%(levelname)-8s] %(message)s'
if not date_format:
date_format = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter(log_format, datefmt=date_format)
handler.setFormatter(formatter)
root_logger.addHandler(handler)
global __LOGFILE_CONFIGURED
global __LOGGING_LOGFILE_HANDLER
__LOGFILE_CONFIGURED = True
__LOGGING_LOGFILE_HANDLER = handler
def setup_extended_logging(opts):
'''
Setup any additional logging handlers, internal or external
'''
if is_extended_logging_configured() is True:
# Don't re-configure external loggers
return
# Explicit late import of salt's loader
import salt.loader
# Let's keep a reference to the current logging handlers
initial_handlers = logging.root.handlers[:]
# Load any additional logging handlers
providers = salt.loader.log_handlers(opts)
# Let's keep track of the new logging handlers so we can sync the stored
# log records with them
additional_handlers = []
for name, get_handlers_func in six.iteritems(providers):
logging.getLogger(__name__).info('Processing `log_handlers.%s`', name)
# Keep a reference to the logging handlers count before getting the
# possible additional ones.
initial_handlers_count = len(logging.root.handlers)
handlers = get_handlers_func()
if isinstance(handlers, types.GeneratorType):
handlers = list(handlers)
elif handlers is False or handlers == [False]:
# A false return value means not configuring any logging handler on
# purpose
logging.getLogger(__name__).info(
'The `log_handlers.%s.setup_handlers()` function returned '
'`False` which means no logging handler was configured on '
'purpose. Continuing...', name
)
continue
else:
# Make sure we have an iterable
handlers = [handlers]
for handler in handlers:
if not handler and \
len(logging.root.handlers) == initial_handlers_count:
logging.getLogger(__name__).info(
'The `log_handlers.%s`, did not return any handlers '
'and the global handlers count did not increase. This '
'could be a sign of `log_handlers.%s` not working as '
'supposed', name, name
)
continue
logging.getLogger(__name__).debug(
'Adding the \'%s\' provided logging handler: \'%s\'',
name, handler
)
additional_handlers.append(handler)
logging.root.addHandler(handler)
for handler in logging.root.handlers:
if handler in initial_handlers:
continue
additional_handlers.append(handler)
# Sync the null logging handler messages with the temporary handler
if LOGGING_STORE_HANDLER is not None:
LOGGING_STORE_HANDLER.sync_with_handlers(additional_handlers)
else:
logging.getLogger(__name__).debug(
'LOGGING_STORE_HANDLER is already None, can\'t sync messages '
'with it'
)
# Remove the temporary queue logging handler
__remove_queue_logging_handler()
# Remove the temporary null logging handler (if it exists)
__remove_null_logging_handler()
global __EXTERNAL_LOGGERS_CONFIGURED
__EXTERNAL_LOGGERS_CONFIGURED = True
def get_multiprocessing_logging_queue():
global __MP_LOGGING_QUEUE
if __MP_IN_MAINPROCESS is False:
# We're not in the MainProcess, return! No Queue shall be instantiated
return __MP_LOGGING_QUEUE
if __MP_LOGGING_QUEUE is None:
__MP_LOGGING_QUEUE = multiprocessing.Queue()
return __MP_LOGGING_QUEUE
def set_multiprocessing_logging_queue(queue):
global __MP_LOGGING_QUEUE
if __MP_LOGGING_QUEUE is not queue:
__MP_LOGGING_QUEUE = queue
def get_multiprocessing_logging_level():
return __MP_LOGGING_LEVEL
def set_multiprocessing_logging_level(log_level):
global __MP_LOGGING_LEVEL
__MP_LOGGING_LEVEL = log_level
def set_multiprocessing_logging_level_by_opts(opts):
'''
This will set the multiprocessing logging level to the lowest
logging level of all the types of logging that are configured.
'''
global __MP_LOGGING_LEVEL
log_levels = [
LOG_LEVELS.get(opts.get('log_level', '').lower(), logging.ERROR),
LOG_LEVELS.get(opts.get('log_level_logfile', '').lower(), logging.ERROR)
]
for level in six.itervalues(opts.get('log_granular_levels', {})):
log_levels.append(
LOG_LEVELS.get(level.lower(), logging.ERROR)
)
__MP_LOGGING_LEVEL = min(log_levels)
def setup_multiprocessing_logging_listener(opts, queue=None):
global __MP_LOGGING_QUEUE_PROCESS
global __MP_LOGGING_LISTENER_CONFIGURED
global __MP_MAINPROCESS_ID
if __MP_IN_MAINPROCESS is False:
# We're not in the MainProcess, return! No logging listener setup shall happen
return
if __MP_LOGGING_LISTENER_CONFIGURED is True:
return
if __MP_MAINPROCESS_ID is not None and __MP_MAINPROCESS_ID != os.getpid():
# We're not in the MainProcess, return! No logging listener setup shall happen
return
__MP_MAINPROCESS_ID = os.getpid()
__MP_LOGGING_QUEUE_PROCESS = multiprocessing.Process(
target=__process_multiprocessing_logging_queue,
args=(opts, queue or get_multiprocessing_logging_queue(),)
)
__MP_LOGGING_QUEUE_PROCESS.daemon = True
__MP_LOGGING_QUEUE_PROCESS.start()
__MP_LOGGING_LISTENER_CONFIGURED = True
def setup_multiprocessing_logging(queue=None):
'''
This code should be called from within a running multiprocessing
process instance.
'''
from salt.utils.platform import is_windows
global __MP_LOGGING_CONFIGURED
global __MP_LOGGING_QUEUE_HANDLER
if __MP_IN_MAINPROCESS is True and not is_windows():
# We're in the MainProcess, return! No multiprocessing logging setup shall happen
# Windows is the exception where we want to set up multiprocessing
# logging in the MainProcess.
return
try:
logging._acquireLock() # pylint: disable=protected-access
if __MP_LOGGING_CONFIGURED is True:
return
# Let's set it to true as fast as possible
__MP_LOGGING_CONFIGURED = True
if __MP_LOGGING_QUEUE_HANDLER is not None:
return
# The temp null and temp queue logging handlers will store messages.
# Since noone will process them, memory usage will grow. If they
# exist, remove them.
__remove_null_logging_handler()
__remove_queue_logging_handler()
# Let's add a queue handler to the logging root handlers
__MP_LOGGING_QUEUE_HANDLER = SaltLogQueueHandler(queue or get_multiprocessing_logging_queue())
logging.root.addHandler(__MP_LOGGING_QUEUE_HANDLER)
# Set the logging root level to the lowest needed level to get all
# desired messages.
log_level = get_multiprocessing_logging_level()
logging.root.setLevel(log_level)
logging.getLogger(__name__).debug(
'Multiprocessing queue logging configured for the process running '
'under PID: %s at log level %s', os.getpid(), log_level
)
# The above logging call will create, in some situations, a futex wait
# lock condition, probably due to the multiprocessing Queue's internal
# lock and semaphore mechanisms.
# A small sleep will allow us not to hit that futex wait lock condition.
time.sleep(0.0001)
finally:
logging._releaseLock() # pylint: disable=protected-access
def shutdown_console_logging():
global __CONSOLE_CONFIGURED
global __LOGGING_CONSOLE_HANDLER
if not __CONSOLE_CONFIGURED or not __LOGGING_CONSOLE_HANDLER:
return
try:
logging._acquireLock()
logging.root.removeHandler(__LOGGING_CONSOLE_HANDLER)
__LOGGING_CONSOLE_HANDLER = None
__CONSOLE_CONFIGURED = False
finally:
logging._releaseLock()
def shutdown_logfile_logging():
global __LOGFILE_CONFIGURED
global __LOGGING_LOGFILE_HANDLER
if not __LOGFILE_CONFIGURED or not __LOGGING_LOGFILE_HANDLER:
return
try:
logging._acquireLock()
logging.root.removeHandler(__LOGGING_LOGFILE_HANDLER)
__LOGGING_LOGFILE_HANDLER = None
__LOGFILE_CONFIGURED = False
finally:
logging._releaseLock()
def shutdown_temp_logging():
__remove_temp_logging_handler()
def shutdown_multiprocessing_logging():
global __MP_LOGGING_CONFIGURED
global __MP_LOGGING_QUEUE_HANDLER
if not __MP_LOGGING_CONFIGURED or not __MP_LOGGING_QUEUE_HANDLER:
return
try:
logging._acquireLock()
# Let's remove the queue handler from the logging root handlers
logging.root.removeHandler(__MP_LOGGING_QUEUE_HANDLER)
__MP_LOGGING_QUEUE_HANDLER = None
__MP_LOGGING_CONFIGURED = False
if not logging.root.handlers:
# Ensure we have at least one logging root handler so
# something can handle logging messages. This case should
# only occur on Windows since on Windows we log to console
# and file through the Multiprocessing Logging Listener.
setup_console_logger()
finally:
logging._releaseLock()
def shutdown_multiprocessing_logging_listener(daemonizing=False):
global __MP_LOGGING_QUEUE
global __MP_LOGGING_QUEUE_PROCESS
global __MP_LOGGING_LISTENER_CONFIGURED
if daemonizing is False and __MP_IN_MAINPROCESS is True:
# We're in the MainProcess and we're not daemonizing, return!
# No multiprocessing logging listener shutdown shall happen
return
if not daemonizing:
# Need to remove the queue handler so that it doesn't try to send
# data over a queue that was shut down on the listener end.
shutdown_multiprocessing_logging()
if __MP_LOGGING_QUEUE_PROCESS is None:
return
if __MP_MAINPROCESS_ID is not None and __MP_MAINPROCESS_ID != os.getpid():
# We're not in the MainProcess, return! No logging listener setup shall happen
return
if __MP_LOGGING_QUEUE_PROCESS.is_alive():
logging.getLogger(__name__).debug('Stopping the multiprocessing logging queue listener')
try:
# Sent None sentinel to stop the logging processing queue
__MP_LOGGING_QUEUE.put(None)
# Let's join the multiprocessing logging handle thread
time.sleep(0.5)
logging.getLogger(__name__).debug('closing multiprocessing queue')
__MP_LOGGING_QUEUE.close()
logging.getLogger(__name__).debug('joining multiprocessing queue thread')
__MP_LOGGING_QUEUE.join_thread()
__MP_LOGGING_QUEUE = None
__MP_LOGGING_QUEUE_PROCESS.join(1)
__MP_LOGGING_QUEUE = None
except IOError:
# We were unable to deliver the sentinel to the queue
# carry on...
pass
if __MP_LOGGING_QUEUE_PROCESS.is_alive():
# Process is still alive!?
__MP_LOGGING_QUEUE_PROCESS.terminate()
__MP_LOGGING_QUEUE_PROCESS = None
__MP_LOGGING_LISTENER_CONFIGURED = False
logging.getLogger(__name__).debug('Stopped the multiprocessing logging queue listener')
def set_logger_level(logger_name, log_level='error'):
'''
Tweak a specific logger's logging level
'''
logging.getLogger(logger_name).setLevel(
LOG_LEVELS.get(log_level.lower(), logging.ERROR)
)
def patch_python_logging_handlers():
'''
Patch the python logging handlers with out mixed-in classes
'''
logging.StreamHandler = StreamHandler
logging.FileHandler = FileHandler
logging.handlers.SysLogHandler = SysLogHandler
logging.handlers.WatchedFileHandler = WatchedFileHandler
logging.handlers.RotatingFileHandler = RotatingFileHandler
if sys.version_info >= (3, 2):
logging.handlers.QueueHandler = QueueHandler
def __process_multiprocessing_logging_queue(opts, queue):
# Avoid circular import
import salt.utils.process
salt.utils.process.appendproctitle('MultiprocessingLoggingQueue')
# Assign UID/GID of user to proc if set
from salt.utils.verify import check_user
user = opts.get('user')
if user:
check_user(user)
from salt.utils.platform import is_windows
if is_windows():
# On Windows, creating a new process doesn't fork (copy the parent
# process image). Due to this, we need to setup all of our logging
# inside this process.
setup_temp_logger()
setup_console_logger(
log_level=opts.get('log_level'),
log_format=opts.get('log_fmt_console'),
date_format=opts.get('log_datefmt_console')
)
setup_logfile_logger(
opts.get('log_file'),
log_level=opts.get('log_level_logfile'),
log_format=opts.get('log_fmt_logfile'),
date_format=opts.get('log_datefmt_logfile'),
max_bytes=opts.get('log_rotate_max_bytes', 0),
backup_count=opts.get('log_rotate_backup_count', 0)
)
setup_extended_logging(opts)
while True:
try:
record = queue.get()
if record is None:
# A sentinel to stop processing the queue
break
# Just log everything, filtering will happen on the main process
# logging handlers
logger = logging.getLogger(record.name)
logger.handle(record)
except (EOFError, KeyboardInterrupt, SystemExit):
break
except Exception as exc: # pylint: disable=broad-except
logging.getLogger(__name__).warning(
'An exception occurred in the multiprocessing logging '
'queue thread: %s', exc, exc_info_on_loglevel=logging.DEBUG
)
def __remove_null_logging_handler():
'''
This function will run once the temporary logging has been configured. It
just removes the NullHandler from the logging handlers.
'''
global LOGGING_NULL_HANDLER
if LOGGING_NULL_HANDLER is None:
# Already removed
return
root_logger = logging.getLogger()
for handler in root_logger.handlers:
if handler is LOGGING_NULL_HANDLER:
root_logger.removeHandler(LOGGING_NULL_HANDLER)
# Redefine the null handler to None so it can be garbage collected
LOGGING_NULL_HANDLER = None
break
def __remove_queue_logging_handler():
'''
This function will run once the additional loggers have been synchronized.
It just removes the QueueLoggingHandler from the logging handlers.
'''
global LOGGING_STORE_HANDLER
if LOGGING_STORE_HANDLER is None:
# Already removed
return
root_logger = logging.getLogger()
for handler in root_logger.handlers:
if handler is LOGGING_STORE_HANDLER:
root_logger.removeHandler(LOGGING_STORE_HANDLER)
# Redefine the null handler to None so it can be garbage collected
LOGGING_STORE_HANDLER = None
break
def __remove_temp_logging_handler():
'''
This function will run once logging has been configured. It just removes
the temporary stream Handler from the logging handlers.
'''
if is_logging_configured():
# In this case, the temporary logging handler has been removed, return!
return
# This should already be done, but...
__remove_null_logging_handler()
root_logger = logging.getLogger()
global LOGGING_TEMP_HANDLER
for handler in root_logger.handlers:
if handler is LOGGING_TEMP_HANDLER:
root_logger.removeHandler(LOGGING_TEMP_HANDLER)
# Redefine the null handler to None so it can be garbage collected
LOGGING_TEMP_HANDLER = None
break
if sys.version_info >= (2, 7):
# Python versions >= 2.7 allow warnings to be redirected to the logging
# system now that it's configured. Let's enable it.
logging.captureWarnings(True)
# Set our own exception handler as the one to use
sys.excepthook = __global_logging_exception_handler
|
saltstack/salt
|
salt/modules/grub_legacy.py
|
conf
|
python
|
def conf():
'''
Parse GRUB conf file
CLI Example:
.. code-block:: bash
salt '*' grub.conf
'''
stanza = ''
stanzas = []
in_stanza = False
ret = {}
pos = 0
try:
with salt.utils.files.fopen(_detect_conf(), 'r') as _fp:
for line in _fp:
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
if line.startswith('\n'):
in_stanza = False
if 'title' in stanza:
stanza += 'order {0}'.format(pos)
pos += 1
stanzas.append(stanza)
stanza = ''
continue
if line.strip().startswith('title'):
if in_stanza:
stanza += 'order {0}'.format(pos)
pos += 1
stanzas.append(stanza)
stanza = ''
else:
in_stanza = True
if in_stanza:
stanza += line
if not in_stanza:
key, value = _parse_line(line)
ret[key] = value
if in_stanza:
if not line.endswith('\n'):
line += '\n'
stanza += line
stanza += 'order {0}'.format(pos)
pos += 1
stanzas.append(stanza)
except (IOError, OSError) as exc:
msg = "Could not read grub config: {0}"
raise CommandExecutionError(msg.format(exc))
ret['stanzas'] = []
for stanza in stanzas:
mydict = {}
for line in stanza.strip().splitlines():
key, value = _parse_line(line)
mydict[key] = value
ret['stanzas'].append(mydict)
return ret
|
Parse GRUB conf file
CLI Example:
.. code-block:: bash
salt '*' grub.conf
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/grub_legacy.py#L55-L115
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n",
"def _parse_line(line=''):\n '''\n Used by conf() to break config lines into\n name/value pairs\n '''\n parts = line.split()\n key = parts.pop(0)\n value = ' '.join(parts)\n return key, value\n"
] |
# -*- coding: utf-8 -*-
'''
Support for GRUB Legacy
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import os
# Import salt libs
import salt.utils.files
import salt.utils.decorators as decorators
from salt.exceptions import CommandExecutionError
# Define the module's virtual name
__virtualname__ = 'grub'
def __virtual__():
'''
Only load the module if grub is installed
'''
if os.path.exists(_detect_conf()):
return __virtualname__
return (False, 'The grub_legacy execution module cannot be loaded: '
'the grub config file does not exist in /boot/grub/')
@decorators.memoize
def _detect_conf():
'''
GRUB conf location differs depending on distro
'''
if __grains__['os_family'] == 'RedHat':
return '/boot/grub/grub.conf'
# Defaults for Ubuntu, Debian, Arch, and others
return '/boot/grub/menu.lst'
def version():
'''
Return server version from grub --version
CLI Example:
.. code-block:: bash
salt '*' grub.version
'''
cmd = '/sbin/grub --version'
out = __salt__['cmd.run'](cmd)
return out
def _parse_line(line=''):
'''
Used by conf() to break config lines into
name/value pairs
'''
parts = line.split()
key = parts.pop(0)
value = ' '.join(parts)
return key, value
|
saltstack/salt
|
salt/modules/grub_legacy.py
|
_parse_line
|
python
|
def _parse_line(line=''):
'''
Used by conf() to break config lines into
name/value pairs
'''
parts = line.split()
key = parts.pop(0)
value = ' '.join(parts)
return key, value
|
Used by conf() to break config lines into
name/value pairs
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/grub_legacy.py#L118-L126
| null |
# -*- coding: utf-8 -*-
'''
Support for GRUB Legacy
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import os
# Import salt libs
import salt.utils.files
import salt.utils.decorators as decorators
from salt.exceptions import CommandExecutionError
# Define the module's virtual name
__virtualname__ = 'grub'
def __virtual__():
'''
Only load the module if grub is installed
'''
if os.path.exists(_detect_conf()):
return __virtualname__
return (False, 'The grub_legacy execution module cannot be loaded: '
'the grub config file does not exist in /boot/grub/')
@decorators.memoize
def _detect_conf():
'''
GRUB conf location differs depending on distro
'''
if __grains__['os_family'] == 'RedHat':
return '/boot/grub/grub.conf'
# Defaults for Ubuntu, Debian, Arch, and others
return '/boot/grub/menu.lst'
def version():
'''
Return server version from grub --version
CLI Example:
.. code-block:: bash
salt '*' grub.version
'''
cmd = '/sbin/grub --version'
out = __salt__['cmd.run'](cmd)
return out
def conf():
'''
Parse GRUB conf file
CLI Example:
.. code-block:: bash
salt '*' grub.conf
'''
stanza = ''
stanzas = []
in_stanza = False
ret = {}
pos = 0
try:
with salt.utils.files.fopen(_detect_conf(), 'r') as _fp:
for line in _fp:
line = salt.utils.stringutils.to_unicode(line)
if line.startswith('#'):
continue
if line.startswith('\n'):
in_stanza = False
if 'title' in stanza:
stanza += 'order {0}'.format(pos)
pos += 1
stanzas.append(stanza)
stanza = ''
continue
if line.strip().startswith('title'):
if in_stanza:
stanza += 'order {0}'.format(pos)
pos += 1
stanzas.append(stanza)
stanza = ''
else:
in_stanza = True
if in_stanza:
stanza += line
if not in_stanza:
key, value = _parse_line(line)
ret[key] = value
if in_stanza:
if not line.endswith('\n'):
line += '\n'
stanza += line
stanza += 'order {0}'.format(pos)
pos += 1
stanzas.append(stanza)
except (IOError, OSError) as exc:
msg = "Could not read grub config: {0}"
raise CommandExecutionError(msg.format(exc))
ret['stanzas'] = []
for stanza in stanzas:
mydict = {}
for line in stanza.strip().splitlines():
key, value = _parse_line(line)
mydict[key] = value
ret['stanzas'].append(mydict)
return ret
|
saltstack/salt
|
salt/modules/nxos_upgrade.py
|
check_upgrade_impact
|
python
|
def check_upgrade_impact(system_image, kickstart_image=None, issu=True, **kwargs):
'''
Display upgrade impact information without actually upgrading the device.
system_image (Mandatory Option)
Path on bootflash: to system image upgrade file.
kickstart_image
Path on bootflash: to kickstart image upgrade file.
(Not required if using combined system/kickstart image file)
Default: None
issu
When True: Attempt In Service Software Upgrade. (non-disruptive)
The upgrade will abort if issu is not possible.
When False: Force (disruptive) Upgrade/Downgrade.
Default: True
timeout
Timeout in seconds for long running 'install all' impact command.
Default: 900
error_pattern
Use the option to pass in a regular expression to search for in the
output of the 'install all impact' command that indicates an error
has occurred. This option is only used when proxy minion connection
type is ssh and otherwise ignored.
.. code-block:: bash
salt 'n9k' nxos.check_upgrade_impact system_image=nxos.9.2.1.bin
salt 'n7k' nxos.check_upgrade_impact system_image=n7000-s2-dk9.8.1.1.bin \\
kickstart_image=n7000-s2-kickstart.8.1.1.bin issu=False
'''
# Input Validation
if not isinstance(issu, bool):
return 'Input Error: The [issu] parameter must be either True or False'
si = system_image
ki = kickstart_image
dev = 'bootflash'
cmd = 'terminal dont-ask ; show install all impact'
if ki is not None:
cmd = cmd + ' kickstart {0}:{1} system {0}:{2}'.format(dev, ki, si)
else:
cmd = cmd + ' nxos {0}:{1}'.format(dev, si)
if issu and ki is None:
cmd = cmd + ' non-disruptive'
log.info("Check upgrade impact using command: '%s'", cmd)
kwargs.update({'timeout': kwargs.get('timeout', 900)})
error_pattern_list = ['Another install procedure may be in progress',
'Pre-upgrade check failed']
kwargs.update({'error_pattern': error_pattern_list})
# Execute Upgrade Impact Check
try:
impact_check = __salt__['nxos.sendline'](cmd, **kwargs)
except CommandExecutionError as e:
impact_check = ast.literal_eval(e.message)
return _parse_upgrade_data(impact_check)
|
Display upgrade impact information without actually upgrading the device.
system_image (Mandatory Option)
Path on bootflash: to system image upgrade file.
kickstart_image
Path on bootflash: to kickstart image upgrade file.
(Not required if using combined system/kickstart image file)
Default: None
issu
When True: Attempt In Service Software Upgrade. (non-disruptive)
The upgrade will abort if issu is not possible.
When False: Force (disruptive) Upgrade/Downgrade.
Default: True
timeout
Timeout in seconds for long running 'install all' impact command.
Default: 900
error_pattern
Use the option to pass in a regular expression to search for in the
output of the 'install all impact' command that indicates an error
has occurred. This option is only used when proxy minion connection
type is ssh and otherwise ignored.
.. code-block:: bash
salt 'n9k' nxos.check_upgrade_impact system_image=nxos.9.2.1.bin
salt 'n7k' nxos.check_upgrade_impact system_image=n7000-s2-dk9.8.1.1.bin \\
kickstart_image=n7000-s2-kickstart.8.1.1.bin issu=False
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos_upgrade.py#L77-L139
|
[
"def _parse_upgrade_data(data):\n '''\n Helper method to parse upgrade data from the NX-OS device.\n '''\n upgrade_result = {}\n upgrade_result['upgrade_data'] = None\n upgrade_result['succeeded'] = False\n upgrade_result['upgrade_required'] = False\n upgrade_result['upgrade_non_disruptive'] = False\n upgrade_result['upgrade_in_progress'] = False\n upgrade_result['installing'] = False\n upgrade_result['module_data'] = {}\n upgrade_result['error_data'] = None\n upgrade_result['backend_processing_error'] = False\n upgrade_result['invalid_command'] = False\n\n # Error handling\n if isinstance(data, string_types) and re.search('Code: 500', data):\n log.info('Detected backend processing error')\n upgrade_result['error_data'] = data\n upgrade_result['backend_processing_error'] = True\n return upgrade_result\n\n if isinstance(data, dict):\n if 'code' in data and data['code'] == '400':\n log.info('Detected client error')\n upgrade_result['error_data'] = data['cli_error']\n\n if re.search('install.*may be in progress', data['cli_error']):\n log.info('Detected install in progress...')\n upgrade_result['installing'] = True\n\n if re.search('Invalid command', data['cli_error']):\n log.info('Detected invalid command...')\n upgrade_result['invalid_command'] = True\n else:\n # If we get here then it's likely we lost access to the device\n # but the upgrade succeeded. We lost the actual upgrade data so\n # set the flag such that impact data is used instead.\n log.info('Probable backend processing error')\n upgrade_result['backend_processing_error'] = True\n return upgrade_result\n\n # Get upgrade data for further parsing\n # Case 1: Command terminal dont-ask returns empty {} that we don't need.\n if isinstance(data, list) and len(data) == 2:\n data = data[1]\n # Case 2: Command terminal dont-ask does not get included.\n if isinstance(data, list) and len(data) == 1:\n data = data[0]\n\n log.info('Parsing NX-OS upgrade data')\n upgrade_result['upgrade_data'] = data\n for line in data.split('\\n'):\n\n log.info('Processing line: (%s)', line)\n\n # Check to see if upgrade is disruptive or non-disruptive\n if re.search(r'non-disruptive', line):\n log.info('Found non-disruptive line')\n upgrade_result['upgrade_non_disruptive'] = True\n\n # Example:\n # Module Image Running-Version(pri:alt) New-Version Upg-Required\n # 1 nxos 7.0(3)I7(5a) 7.0(3)I7(5a) no\n # 1 bios v07.65(09/04/2018) v07.64(05/16/2018) no\n mo = re.search(r'(\\d+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(yes|no)', line)\n if mo:\n log.info('Matched Module Running/New Version Upg-Req Line')\n bk = 'module_data' # base key\n g1 = mo.group(1)\n g2 = mo.group(2)\n g3 = mo.group(3)\n g4 = mo.group(4)\n g5 = mo.group(5)\n mk = 'module {0}:image {1}'.format(g1, g2) # module key\n upgrade_result[bk][mk] = {}\n upgrade_result[bk][mk]['running_version'] = g3\n upgrade_result[bk][mk]['new_version'] = g4\n if g5 == 'yes':\n upgrade_result['upgrade_required'] = True\n upgrade_result[bk][mk]['upgrade_required'] = True\n continue\n\n # The following lines indicate a successfull upgrade.\n if re.search(r'Install has been successful', line):\n log.info('Install successful line')\n upgrade_result['succeeded'] = True\n continue\n\n if re.search(r'Finishing the upgrade, switch will reboot in', line):\n log.info('Finishing upgrade line')\n upgrade_result['upgrade_in_progress'] = True\n continue\n\n if re.search(r'Switch will be reloaded for disruptive upgrade', line):\n log.info('Switch will be reloaded line')\n upgrade_result['upgrade_in_progress'] = True\n continue\n\n if re.search(r'Switching over onto standby', line):\n log.info('Switching over onto standby line')\n upgrade_result['upgrade_in_progress'] = True\n continue\n\n return upgrade_result\n"
] |
# -*- coding: utf-8 -*-
# Copyright (c) 2018 Cisco and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''
Execution module to upgrade Cisco NX-OS Switches.
.. versionadded:: xxxx.xx.x
This module supports execution using a Proxy Minion or Native Minion:
1) Proxy Minion: Connect over SSH or NX-API HTTP(S).
See :mod:`salt.proxy.nxos <salt.proxy.nxos>` for proxy minion setup details.
2) Native Minion: Connect over NX-API Unix Domain Socket (UDS).
Install the minion inside the GuestShell running on the NX-OS device.
:maturity: new
:platform: nxos
:codeauthor: Michael G Wiebe
.. note::
To use this module over remote NX-API the feature must be enabled on the
NX-OS device by executing ``feature nxapi`` in configuration mode.
This is not required for NX-API over UDS.
Configuration example:
.. code-block:: bash
switch# conf t
switch(config)# feature nxapi
To check that NX-API is properly enabled, execute ``show nxapi``.
Output example:
.. code-block:: bash
switch# show nxapi
nxapi enabled
HTTPS Listen on port 443
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python stdlib
import logging
import re
import ast
import time
from salt.ext.six import string_types
# Import Salt libs
from salt.exceptions import (NxosError, CommandExecutionError)
from salt.ext.six.moves import range
__virtualname__ = 'nxos'
__virtual_aliases__ = ('nxos_upgrade',)
log = logging.getLogger(__name__)
def __virtual__():
return __virtualname__
def upgrade(system_image, kickstart_image=None, issu=True, **kwargs):
'''
Upgrade NX-OS switch.
system_image (Mandatory Option)
Path on bootflash: to system image upgrade file.
kickstart_image
Path on bootflash: to kickstart image upgrade file.
(Not required if using combined system/kickstart image file)
Default: None
issu
Set this option to True when an In Service Software Upgrade or
non-disruptive upgrade is required. The upgrade will abort if issu is
not possible.
Default: True
timeout
Timeout in seconds for long running 'install all' upgrade command.
Default: 900
error_pattern
Use the option to pass in a regular expression to search for in the
output of the 'install all upgrade command that indicates an error
has occurred. This option is only used when proxy minion connection
type is ssh and otherwise ignored.
.. code-block:: bash
salt 'n9k' nxos.upgrade system_image=nxos.9.2.1.bin
salt 'n7k' nxos.upgrade system_image=n7000-s2-dk9.8.1.1.bin \\
kickstart_image=n7000-s2-kickstart.8.1.1.bin issu=False
'''
# Input Validation
if not isinstance(issu, bool):
return 'Input Error: The [issu] parameter must be either True or False'
impact = None
upgrade = None
maxtry = 60
for attempt in range(1, maxtry):
# Gather impact data first. It's possible to loose upgrade data
# when the switch reloads or switches over to the inactive supervisor.
# The impact data will be used if data being collected during the
# upgrade is lost.
if impact is None:
log.info('Gathering impact data')
impact = check_upgrade_impact(system_image, kickstart_image,
issu, **kwargs)
if impact['installing']:
log.info('Another show impact in progress... wait and retry')
time.sleep(30)
continue
# If we are upgrading from a system running a separate system and
# kickstart image to a combined image or vice versa then the impact
# check will return a syntax error as it's not supported.
# Skip the impact check in this case and attempt the upgrade.
if impact['invalid_command']:
impact = False
continue
log.info('Impact data gathered:\n%s', impact)
# Check to see if conditions are sufficent to return the impact
# data and not proceed with the actual upgrade.
#
# Impact data indicates the upgrade or downgrade will fail
if impact['error_data']:
return impact
# Requested ISSU but ISSU is not possible
if issu and not impact['upgrade_non_disruptive']:
impact['error_data'] = impact['upgrade_data']
return impact
# Impact data indicates a failure and no module_data collected
if not impact['succeeded'] and not impact['module_data']:
impact['error_data'] = impact['upgrade_data']
return impact
# Impact data indicates switch already running desired image
if not impact['upgrade_required']:
impact['succeeded'] = True
return impact
# If we get here, impact data indicates upgrade is needed.
upgrade = _upgrade(system_image, kickstart_image, issu, **kwargs)
if upgrade['installing']:
log.info('Another install is in progress... wait and retry')
time.sleep(30)
continue
# If the issu option is False and this upgrade request includes a
# kickstart image then the 'force' option is used. This option is
# only available in certain image sets.
if upgrade['invalid_command']:
log_msg = 'The [issu] option was set to False for this upgrade.'
log_msg = log_msg + ' Attempt was made to ugrade using the force'
log_msg = log_msg + ' keyword which is not supported in this'
log_msg = log_msg + ' image. Set [issu=True] and re-try.'
upgrade['upgrade_data'] = log_msg
break
break
# Check for errors and return upgrade result:
if upgrade['backend_processing_error']:
# This means we received a backend processing error from the transport
# and lost the upgrade data. This also indicates that the upgrade
# is in progress so use the impact data for logging purposes.
impact['upgrade_in_progress'] = True
return impact
return upgrade
def _upgrade(system_image, kickstart_image, issu, **kwargs):
'''
Helper method that does the heavy lifting for upgrades.
'''
si = system_image
ki = kickstart_image
dev = 'bootflash'
cmd = 'terminal dont-ask ; install all'
if ki is None:
logmsg = 'Upgrading device using combined system/kickstart image.'
logmsg += '\nSystem Image: {}'.format(si)
cmd = cmd + ' nxos {0}:{1}'.format(dev, si)
if issu:
cmd = cmd + ' non-disruptive'
else:
logmsg = 'Upgrading device using separate system/kickstart images.'
logmsg += '\nSystem Image: {}'.format(si)
logmsg += '\nKickstart Image: {}'.format(ki)
if not issu:
log.info('Attempting upgrade using force option')
cmd = cmd + ' force'
cmd = cmd + ' kickstart {0}:{1} system {0}:{2}'.format(dev, ki, si)
if issu:
logmsg += '\nIn Service Software Upgrade/Downgrade (non-disruptive) requested.'
else:
logmsg += '\nDisruptive Upgrade/Downgrade requested.'
log.info(logmsg)
log.info("Begin upgrade using command: '%s'", cmd)
kwargs.update({'timeout': kwargs.get('timeout', 900)})
error_pattern_list = ['Another install procedure may be in progress']
kwargs.update({'error_pattern': error_pattern_list})
# Begin Actual Upgrade
try:
upgrade_result = __salt__['nxos.sendline'](cmd, **kwargs)
except CommandExecutionError as e:
upgrade_result = ast.literal_eval(e.message)
except NxosError as e:
if re.search('Code: 500', e.message):
upgrade_result = e.message
else:
upgrade_result = ast.literal_eval(e.message)
return _parse_upgrade_data(upgrade_result)
def _parse_upgrade_data(data):
'''
Helper method to parse upgrade data from the NX-OS device.
'''
upgrade_result = {}
upgrade_result['upgrade_data'] = None
upgrade_result['succeeded'] = False
upgrade_result['upgrade_required'] = False
upgrade_result['upgrade_non_disruptive'] = False
upgrade_result['upgrade_in_progress'] = False
upgrade_result['installing'] = False
upgrade_result['module_data'] = {}
upgrade_result['error_data'] = None
upgrade_result['backend_processing_error'] = False
upgrade_result['invalid_command'] = False
# Error handling
if isinstance(data, string_types) and re.search('Code: 500', data):
log.info('Detected backend processing error')
upgrade_result['error_data'] = data
upgrade_result['backend_processing_error'] = True
return upgrade_result
if isinstance(data, dict):
if 'code' in data and data['code'] == '400':
log.info('Detected client error')
upgrade_result['error_data'] = data['cli_error']
if re.search('install.*may be in progress', data['cli_error']):
log.info('Detected install in progress...')
upgrade_result['installing'] = True
if re.search('Invalid command', data['cli_error']):
log.info('Detected invalid command...')
upgrade_result['invalid_command'] = True
else:
# If we get here then it's likely we lost access to the device
# but the upgrade succeeded. We lost the actual upgrade data so
# set the flag such that impact data is used instead.
log.info('Probable backend processing error')
upgrade_result['backend_processing_error'] = True
return upgrade_result
# Get upgrade data for further parsing
# Case 1: Command terminal dont-ask returns empty {} that we don't need.
if isinstance(data, list) and len(data) == 2:
data = data[1]
# Case 2: Command terminal dont-ask does not get included.
if isinstance(data, list) and len(data) == 1:
data = data[0]
log.info('Parsing NX-OS upgrade data')
upgrade_result['upgrade_data'] = data
for line in data.split('\n'):
log.info('Processing line: (%s)', line)
# Check to see if upgrade is disruptive or non-disruptive
if re.search(r'non-disruptive', line):
log.info('Found non-disruptive line')
upgrade_result['upgrade_non_disruptive'] = True
# Example:
# Module Image Running-Version(pri:alt) New-Version Upg-Required
# 1 nxos 7.0(3)I7(5a) 7.0(3)I7(5a) no
# 1 bios v07.65(09/04/2018) v07.64(05/16/2018) no
mo = re.search(r'(\d+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(yes|no)', line)
if mo:
log.info('Matched Module Running/New Version Upg-Req Line')
bk = 'module_data' # base key
g1 = mo.group(1)
g2 = mo.group(2)
g3 = mo.group(3)
g4 = mo.group(4)
g5 = mo.group(5)
mk = 'module {0}:image {1}'.format(g1, g2) # module key
upgrade_result[bk][mk] = {}
upgrade_result[bk][mk]['running_version'] = g3
upgrade_result[bk][mk]['new_version'] = g4
if g5 == 'yes':
upgrade_result['upgrade_required'] = True
upgrade_result[bk][mk]['upgrade_required'] = True
continue
# The following lines indicate a successfull upgrade.
if re.search(r'Install has been successful', line):
log.info('Install successful line')
upgrade_result['succeeded'] = True
continue
if re.search(r'Finishing the upgrade, switch will reboot in', line):
log.info('Finishing upgrade line')
upgrade_result['upgrade_in_progress'] = True
continue
if re.search(r'Switch will be reloaded for disruptive upgrade', line):
log.info('Switch will be reloaded line')
upgrade_result['upgrade_in_progress'] = True
continue
if re.search(r'Switching over onto standby', line):
log.info('Switching over onto standby line')
upgrade_result['upgrade_in_progress'] = True
continue
return upgrade_result
|
saltstack/salt
|
salt/modules/nxos_upgrade.py
|
upgrade
|
python
|
def upgrade(system_image, kickstart_image=None, issu=True, **kwargs):
'''
Upgrade NX-OS switch.
system_image (Mandatory Option)
Path on bootflash: to system image upgrade file.
kickstart_image
Path on bootflash: to kickstart image upgrade file.
(Not required if using combined system/kickstart image file)
Default: None
issu
Set this option to True when an In Service Software Upgrade or
non-disruptive upgrade is required. The upgrade will abort if issu is
not possible.
Default: True
timeout
Timeout in seconds for long running 'install all' upgrade command.
Default: 900
error_pattern
Use the option to pass in a regular expression to search for in the
output of the 'install all upgrade command that indicates an error
has occurred. This option is only used when proxy minion connection
type is ssh and otherwise ignored.
.. code-block:: bash
salt 'n9k' nxos.upgrade system_image=nxos.9.2.1.bin
salt 'n7k' nxos.upgrade system_image=n7000-s2-dk9.8.1.1.bin \\
kickstart_image=n7000-s2-kickstart.8.1.1.bin issu=False
'''
# Input Validation
if not isinstance(issu, bool):
return 'Input Error: The [issu] parameter must be either True or False'
impact = None
upgrade = None
maxtry = 60
for attempt in range(1, maxtry):
# Gather impact data first. It's possible to loose upgrade data
# when the switch reloads or switches over to the inactive supervisor.
# The impact data will be used if data being collected during the
# upgrade is lost.
if impact is None:
log.info('Gathering impact data')
impact = check_upgrade_impact(system_image, kickstart_image,
issu, **kwargs)
if impact['installing']:
log.info('Another show impact in progress... wait and retry')
time.sleep(30)
continue
# If we are upgrading from a system running a separate system and
# kickstart image to a combined image or vice versa then the impact
# check will return a syntax error as it's not supported.
# Skip the impact check in this case and attempt the upgrade.
if impact['invalid_command']:
impact = False
continue
log.info('Impact data gathered:\n%s', impact)
# Check to see if conditions are sufficent to return the impact
# data and not proceed with the actual upgrade.
#
# Impact data indicates the upgrade or downgrade will fail
if impact['error_data']:
return impact
# Requested ISSU but ISSU is not possible
if issu and not impact['upgrade_non_disruptive']:
impact['error_data'] = impact['upgrade_data']
return impact
# Impact data indicates a failure and no module_data collected
if not impact['succeeded'] and not impact['module_data']:
impact['error_data'] = impact['upgrade_data']
return impact
# Impact data indicates switch already running desired image
if not impact['upgrade_required']:
impact['succeeded'] = True
return impact
# If we get here, impact data indicates upgrade is needed.
upgrade = _upgrade(system_image, kickstart_image, issu, **kwargs)
if upgrade['installing']:
log.info('Another install is in progress... wait and retry')
time.sleep(30)
continue
# If the issu option is False and this upgrade request includes a
# kickstart image then the 'force' option is used. This option is
# only available in certain image sets.
if upgrade['invalid_command']:
log_msg = 'The [issu] option was set to False for this upgrade.'
log_msg = log_msg + ' Attempt was made to ugrade using the force'
log_msg = log_msg + ' keyword which is not supported in this'
log_msg = log_msg + ' image. Set [issu=True] and re-try.'
upgrade['upgrade_data'] = log_msg
break
break
# Check for errors and return upgrade result:
if upgrade['backend_processing_error']:
# This means we received a backend processing error from the transport
# and lost the upgrade data. This also indicates that the upgrade
# is in progress so use the impact data for logging purposes.
impact['upgrade_in_progress'] = True
return impact
return upgrade
|
Upgrade NX-OS switch.
system_image (Mandatory Option)
Path on bootflash: to system image upgrade file.
kickstart_image
Path on bootflash: to kickstart image upgrade file.
(Not required if using combined system/kickstart image file)
Default: None
issu
Set this option to True when an In Service Software Upgrade or
non-disruptive upgrade is required. The upgrade will abort if issu is
not possible.
Default: True
timeout
Timeout in seconds for long running 'install all' upgrade command.
Default: 900
error_pattern
Use the option to pass in a regular expression to search for in the
output of the 'install all upgrade command that indicates an error
has occurred. This option is only used when proxy minion connection
type is ssh and otherwise ignored.
.. code-block:: bash
salt 'n9k' nxos.upgrade system_image=nxos.9.2.1.bin
salt 'n7k' nxos.upgrade system_image=n7000-s2-dk9.8.1.1.bin \\
kickstart_image=n7000-s2-kickstart.8.1.1.bin issu=False
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos_upgrade.py#L142-L248
|
[
"def check_upgrade_impact(system_image, kickstart_image=None, issu=True, **kwargs):\n '''\n Display upgrade impact information without actually upgrading the device.\n\n system_image (Mandatory Option)\n Path on bootflash: to system image upgrade file.\n\n kickstart_image\n Path on bootflash: to kickstart image upgrade file.\n (Not required if using combined system/kickstart image file)\n Default: None\n\n issu\n When True: Attempt In Service Software Upgrade. (non-disruptive)\n The upgrade will abort if issu is not possible.\n When False: Force (disruptive) Upgrade/Downgrade.\n Default: True\n\n timeout\n Timeout in seconds for long running 'install all' impact command.\n Default: 900\n\n error_pattern\n Use the option to pass in a regular expression to search for in the\n output of the 'install all impact' command that indicates an error\n has occurred. This option is only used when proxy minion connection\n type is ssh and otherwise ignored.\n\n .. code-block:: bash\n\n salt 'n9k' nxos.check_upgrade_impact system_image=nxos.9.2.1.bin\n salt 'n7k' nxos.check_upgrade_impact system_image=n7000-s2-dk9.8.1.1.bin \\\\\n kickstart_image=n7000-s2-kickstart.8.1.1.bin issu=False\n '''\n # Input Validation\n if not isinstance(issu, bool):\n return 'Input Error: The [issu] parameter must be either True or False'\n\n si = system_image\n ki = kickstart_image\n dev = 'bootflash'\n cmd = 'terminal dont-ask ; show install all impact'\n\n if ki is not None:\n cmd = cmd + ' kickstart {0}:{1} system {0}:{2}'.format(dev, ki, si)\n else:\n cmd = cmd + ' nxos {0}:{1}'.format(dev, si)\n\n if issu and ki is None:\n cmd = cmd + ' non-disruptive'\n\n log.info(\"Check upgrade impact using command: '%s'\", cmd)\n kwargs.update({'timeout': kwargs.get('timeout', 900)})\n error_pattern_list = ['Another install procedure may be in progress',\n 'Pre-upgrade check failed']\n kwargs.update({'error_pattern': error_pattern_list})\n\n # Execute Upgrade Impact Check\n try:\n impact_check = __salt__['nxos.sendline'](cmd, **kwargs)\n except CommandExecutionError as e:\n impact_check = ast.literal_eval(e.message)\n return _parse_upgrade_data(impact_check)\n",
"def _upgrade(system_image, kickstart_image, issu, **kwargs):\n '''\n Helper method that does the heavy lifting for upgrades.\n '''\n si = system_image\n ki = kickstart_image\n dev = 'bootflash'\n cmd = 'terminal dont-ask ; install all'\n\n if ki is None:\n logmsg = 'Upgrading device using combined system/kickstart image.'\n logmsg += '\\nSystem Image: {}'.format(si)\n cmd = cmd + ' nxos {0}:{1}'.format(dev, si)\n if issu:\n cmd = cmd + ' non-disruptive'\n else:\n logmsg = 'Upgrading device using separate system/kickstart images.'\n logmsg += '\\nSystem Image: {}'.format(si)\n logmsg += '\\nKickstart Image: {}'.format(ki)\n if not issu:\n log.info('Attempting upgrade using force option')\n cmd = cmd + ' force'\n cmd = cmd + ' kickstart {0}:{1} system {0}:{2}'.format(dev, ki, si)\n\n if issu:\n logmsg += '\\nIn Service Software Upgrade/Downgrade (non-disruptive) requested.'\n else:\n logmsg += '\\nDisruptive Upgrade/Downgrade requested.'\n\n log.info(logmsg)\n log.info(\"Begin upgrade using command: '%s'\", cmd)\n\n kwargs.update({'timeout': kwargs.get('timeout', 900)})\n error_pattern_list = ['Another install procedure may be in progress']\n kwargs.update({'error_pattern': error_pattern_list})\n\n # Begin Actual Upgrade\n try:\n upgrade_result = __salt__['nxos.sendline'](cmd, **kwargs)\n except CommandExecutionError as e:\n upgrade_result = ast.literal_eval(e.message)\n except NxosError as e:\n if re.search('Code: 500', e.message):\n upgrade_result = e.message\n else:\n upgrade_result = ast.literal_eval(e.message)\n return _parse_upgrade_data(upgrade_result)\n"
] |
# -*- coding: utf-8 -*-
# Copyright (c) 2018 Cisco and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''
Execution module to upgrade Cisco NX-OS Switches.
.. versionadded:: xxxx.xx.x
This module supports execution using a Proxy Minion or Native Minion:
1) Proxy Minion: Connect over SSH or NX-API HTTP(S).
See :mod:`salt.proxy.nxos <salt.proxy.nxos>` for proxy minion setup details.
2) Native Minion: Connect over NX-API Unix Domain Socket (UDS).
Install the minion inside the GuestShell running on the NX-OS device.
:maturity: new
:platform: nxos
:codeauthor: Michael G Wiebe
.. note::
To use this module over remote NX-API the feature must be enabled on the
NX-OS device by executing ``feature nxapi`` in configuration mode.
This is not required for NX-API over UDS.
Configuration example:
.. code-block:: bash
switch# conf t
switch(config)# feature nxapi
To check that NX-API is properly enabled, execute ``show nxapi``.
Output example:
.. code-block:: bash
switch# show nxapi
nxapi enabled
HTTPS Listen on port 443
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python stdlib
import logging
import re
import ast
import time
from salt.ext.six import string_types
# Import Salt libs
from salt.exceptions import (NxosError, CommandExecutionError)
from salt.ext.six.moves import range
__virtualname__ = 'nxos'
__virtual_aliases__ = ('nxos_upgrade',)
log = logging.getLogger(__name__)
def __virtual__():
return __virtualname__
def check_upgrade_impact(system_image, kickstart_image=None, issu=True, **kwargs):
'''
Display upgrade impact information without actually upgrading the device.
system_image (Mandatory Option)
Path on bootflash: to system image upgrade file.
kickstart_image
Path on bootflash: to kickstart image upgrade file.
(Not required if using combined system/kickstart image file)
Default: None
issu
When True: Attempt In Service Software Upgrade. (non-disruptive)
The upgrade will abort if issu is not possible.
When False: Force (disruptive) Upgrade/Downgrade.
Default: True
timeout
Timeout in seconds for long running 'install all' impact command.
Default: 900
error_pattern
Use the option to pass in a regular expression to search for in the
output of the 'install all impact' command that indicates an error
has occurred. This option is only used when proxy minion connection
type is ssh and otherwise ignored.
.. code-block:: bash
salt 'n9k' nxos.check_upgrade_impact system_image=nxos.9.2.1.bin
salt 'n7k' nxos.check_upgrade_impact system_image=n7000-s2-dk9.8.1.1.bin \\
kickstart_image=n7000-s2-kickstart.8.1.1.bin issu=False
'''
# Input Validation
if not isinstance(issu, bool):
return 'Input Error: The [issu] parameter must be either True or False'
si = system_image
ki = kickstart_image
dev = 'bootflash'
cmd = 'terminal dont-ask ; show install all impact'
if ki is not None:
cmd = cmd + ' kickstart {0}:{1} system {0}:{2}'.format(dev, ki, si)
else:
cmd = cmd + ' nxos {0}:{1}'.format(dev, si)
if issu and ki is None:
cmd = cmd + ' non-disruptive'
log.info("Check upgrade impact using command: '%s'", cmd)
kwargs.update({'timeout': kwargs.get('timeout', 900)})
error_pattern_list = ['Another install procedure may be in progress',
'Pre-upgrade check failed']
kwargs.update({'error_pattern': error_pattern_list})
# Execute Upgrade Impact Check
try:
impact_check = __salt__['nxos.sendline'](cmd, **kwargs)
except CommandExecutionError as e:
impact_check = ast.literal_eval(e.message)
return _parse_upgrade_data(impact_check)
def _upgrade(system_image, kickstart_image, issu, **kwargs):
'''
Helper method that does the heavy lifting for upgrades.
'''
si = system_image
ki = kickstart_image
dev = 'bootflash'
cmd = 'terminal dont-ask ; install all'
if ki is None:
logmsg = 'Upgrading device using combined system/kickstart image.'
logmsg += '\nSystem Image: {}'.format(si)
cmd = cmd + ' nxos {0}:{1}'.format(dev, si)
if issu:
cmd = cmd + ' non-disruptive'
else:
logmsg = 'Upgrading device using separate system/kickstart images.'
logmsg += '\nSystem Image: {}'.format(si)
logmsg += '\nKickstart Image: {}'.format(ki)
if not issu:
log.info('Attempting upgrade using force option')
cmd = cmd + ' force'
cmd = cmd + ' kickstart {0}:{1} system {0}:{2}'.format(dev, ki, si)
if issu:
logmsg += '\nIn Service Software Upgrade/Downgrade (non-disruptive) requested.'
else:
logmsg += '\nDisruptive Upgrade/Downgrade requested.'
log.info(logmsg)
log.info("Begin upgrade using command: '%s'", cmd)
kwargs.update({'timeout': kwargs.get('timeout', 900)})
error_pattern_list = ['Another install procedure may be in progress']
kwargs.update({'error_pattern': error_pattern_list})
# Begin Actual Upgrade
try:
upgrade_result = __salt__['nxos.sendline'](cmd, **kwargs)
except CommandExecutionError as e:
upgrade_result = ast.literal_eval(e.message)
except NxosError as e:
if re.search('Code: 500', e.message):
upgrade_result = e.message
else:
upgrade_result = ast.literal_eval(e.message)
return _parse_upgrade_data(upgrade_result)
def _parse_upgrade_data(data):
'''
Helper method to parse upgrade data from the NX-OS device.
'''
upgrade_result = {}
upgrade_result['upgrade_data'] = None
upgrade_result['succeeded'] = False
upgrade_result['upgrade_required'] = False
upgrade_result['upgrade_non_disruptive'] = False
upgrade_result['upgrade_in_progress'] = False
upgrade_result['installing'] = False
upgrade_result['module_data'] = {}
upgrade_result['error_data'] = None
upgrade_result['backend_processing_error'] = False
upgrade_result['invalid_command'] = False
# Error handling
if isinstance(data, string_types) and re.search('Code: 500', data):
log.info('Detected backend processing error')
upgrade_result['error_data'] = data
upgrade_result['backend_processing_error'] = True
return upgrade_result
if isinstance(data, dict):
if 'code' in data and data['code'] == '400':
log.info('Detected client error')
upgrade_result['error_data'] = data['cli_error']
if re.search('install.*may be in progress', data['cli_error']):
log.info('Detected install in progress...')
upgrade_result['installing'] = True
if re.search('Invalid command', data['cli_error']):
log.info('Detected invalid command...')
upgrade_result['invalid_command'] = True
else:
# If we get here then it's likely we lost access to the device
# but the upgrade succeeded. We lost the actual upgrade data so
# set the flag such that impact data is used instead.
log.info('Probable backend processing error')
upgrade_result['backend_processing_error'] = True
return upgrade_result
# Get upgrade data for further parsing
# Case 1: Command terminal dont-ask returns empty {} that we don't need.
if isinstance(data, list) and len(data) == 2:
data = data[1]
# Case 2: Command terminal dont-ask does not get included.
if isinstance(data, list) and len(data) == 1:
data = data[0]
log.info('Parsing NX-OS upgrade data')
upgrade_result['upgrade_data'] = data
for line in data.split('\n'):
log.info('Processing line: (%s)', line)
# Check to see if upgrade is disruptive or non-disruptive
if re.search(r'non-disruptive', line):
log.info('Found non-disruptive line')
upgrade_result['upgrade_non_disruptive'] = True
# Example:
# Module Image Running-Version(pri:alt) New-Version Upg-Required
# 1 nxos 7.0(3)I7(5a) 7.0(3)I7(5a) no
# 1 bios v07.65(09/04/2018) v07.64(05/16/2018) no
mo = re.search(r'(\d+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(yes|no)', line)
if mo:
log.info('Matched Module Running/New Version Upg-Req Line')
bk = 'module_data' # base key
g1 = mo.group(1)
g2 = mo.group(2)
g3 = mo.group(3)
g4 = mo.group(4)
g5 = mo.group(5)
mk = 'module {0}:image {1}'.format(g1, g2) # module key
upgrade_result[bk][mk] = {}
upgrade_result[bk][mk]['running_version'] = g3
upgrade_result[bk][mk]['new_version'] = g4
if g5 == 'yes':
upgrade_result['upgrade_required'] = True
upgrade_result[bk][mk]['upgrade_required'] = True
continue
# The following lines indicate a successfull upgrade.
if re.search(r'Install has been successful', line):
log.info('Install successful line')
upgrade_result['succeeded'] = True
continue
if re.search(r'Finishing the upgrade, switch will reboot in', line):
log.info('Finishing upgrade line')
upgrade_result['upgrade_in_progress'] = True
continue
if re.search(r'Switch will be reloaded for disruptive upgrade', line):
log.info('Switch will be reloaded line')
upgrade_result['upgrade_in_progress'] = True
continue
if re.search(r'Switching over onto standby', line):
log.info('Switching over onto standby line')
upgrade_result['upgrade_in_progress'] = True
continue
return upgrade_result
|
saltstack/salt
|
salt/modules/nxos_upgrade.py
|
_upgrade
|
python
|
def _upgrade(system_image, kickstart_image, issu, **kwargs):
'''
Helper method that does the heavy lifting for upgrades.
'''
si = system_image
ki = kickstart_image
dev = 'bootflash'
cmd = 'terminal dont-ask ; install all'
if ki is None:
logmsg = 'Upgrading device using combined system/kickstart image.'
logmsg += '\nSystem Image: {}'.format(si)
cmd = cmd + ' nxos {0}:{1}'.format(dev, si)
if issu:
cmd = cmd + ' non-disruptive'
else:
logmsg = 'Upgrading device using separate system/kickstart images.'
logmsg += '\nSystem Image: {}'.format(si)
logmsg += '\nKickstart Image: {}'.format(ki)
if not issu:
log.info('Attempting upgrade using force option')
cmd = cmd + ' force'
cmd = cmd + ' kickstart {0}:{1} system {0}:{2}'.format(dev, ki, si)
if issu:
logmsg += '\nIn Service Software Upgrade/Downgrade (non-disruptive) requested.'
else:
logmsg += '\nDisruptive Upgrade/Downgrade requested.'
log.info(logmsg)
log.info("Begin upgrade using command: '%s'", cmd)
kwargs.update({'timeout': kwargs.get('timeout', 900)})
error_pattern_list = ['Another install procedure may be in progress']
kwargs.update({'error_pattern': error_pattern_list})
# Begin Actual Upgrade
try:
upgrade_result = __salt__['nxos.sendline'](cmd, **kwargs)
except CommandExecutionError as e:
upgrade_result = ast.literal_eval(e.message)
except NxosError as e:
if re.search('Code: 500', e.message):
upgrade_result = e.message
else:
upgrade_result = ast.literal_eval(e.message)
return _parse_upgrade_data(upgrade_result)
|
Helper method that does the heavy lifting for upgrades.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos_upgrade.py#L251-L297
|
[
"def _parse_upgrade_data(data):\n '''\n Helper method to parse upgrade data from the NX-OS device.\n '''\n upgrade_result = {}\n upgrade_result['upgrade_data'] = None\n upgrade_result['succeeded'] = False\n upgrade_result['upgrade_required'] = False\n upgrade_result['upgrade_non_disruptive'] = False\n upgrade_result['upgrade_in_progress'] = False\n upgrade_result['installing'] = False\n upgrade_result['module_data'] = {}\n upgrade_result['error_data'] = None\n upgrade_result['backend_processing_error'] = False\n upgrade_result['invalid_command'] = False\n\n # Error handling\n if isinstance(data, string_types) and re.search('Code: 500', data):\n log.info('Detected backend processing error')\n upgrade_result['error_data'] = data\n upgrade_result['backend_processing_error'] = True\n return upgrade_result\n\n if isinstance(data, dict):\n if 'code' in data and data['code'] == '400':\n log.info('Detected client error')\n upgrade_result['error_data'] = data['cli_error']\n\n if re.search('install.*may be in progress', data['cli_error']):\n log.info('Detected install in progress...')\n upgrade_result['installing'] = True\n\n if re.search('Invalid command', data['cli_error']):\n log.info('Detected invalid command...')\n upgrade_result['invalid_command'] = True\n else:\n # If we get here then it's likely we lost access to the device\n # but the upgrade succeeded. We lost the actual upgrade data so\n # set the flag such that impact data is used instead.\n log.info('Probable backend processing error')\n upgrade_result['backend_processing_error'] = True\n return upgrade_result\n\n # Get upgrade data for further parsing\n # Case 1: Command terminal dont-ask returns empty {} that we don't need.\n if isinstance(data, list) and len(data) == 2:\n data = data[1]\n # Case 2: Command terminal dont-ask does not get included.\n if isinstance(data, list) and len(data) == 1:\n data = data[0]\n\n log.info('Parsing NX-OS upgrade data')\n upgrade_result['upgrade_data'] = data\n for line in data.split('\\n'):\n\n log.info('Processing line: (%s)', line)\n\n # Check to see if upgrade is disruptive or non-disruptive\n if re.search(r'non-disruptive', line):\n log.info('Found non-disruptive line')\n upgrade_result['upgrade_non_disruptive'] = True\n\n # Example:\n # Module Image Running-Version(pri:alt) New-Version Upg-Required\n # 1 nxos 7.0(3)I7(5a) 7.0(3)I7(5a) no\n # 1 bios v07.65(09/04/2018) v07.64(05/16/2018) no\n mo = re.search(r'(\\d+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(yes|no)', line)\n if mo:\n log.info('Matched Module Running/New Version Upg-Req Line')\n bk = 'module_data' # base key\n g1 = mo.group(1)\n g2 = mo.group(2)\n g3 = mo.group(3)\n g4 = mo.group(4)\n g5 = mo.group(5)\n mk = 'module {0}:image {1}'.format(g1, g2) # module key\n upgrade_result[bk][mk] = {}\n upgrade_result[bk][mk]['running_version'] = g3\n upgrade_result[bk][mk]['new_version'] = g4\n if g5 == 'yes':\n upgrade_result['upgrade_required'] = True\n upgrade_result[bk][mk]['upgrade_required'] = True\n continue\n\n # The following lines indicate a successfull upgrade.\n if re.search(r'Install has been successful', line):\n log.info('Install successful line')\n upgrade_result['succeeded'] = True\n continue\n\n if re.search(r'Finishing the upgrade, switch will reboot in', line):\n log.info('Finishing upgrade line')\n upgrade_result['upgrade_in_progress'] = True\n continue\n\n if re.search(r'Switch will be reloaded for disruptive upgrade', line):\n log.info('Switch will be reloaded line')\n upgrade_result['upgrade_in_progress'] = True\n continue\n\n if re.search(r'Switching over onto standby', line):\n log.info('Switching over onto standby line')\n upgrade_result['upgrade_in_progress'] = True\n continue\n\n return upgrade_result\n"
] |
# -*- coding: utf-8 -*-
# Copyright (c) 2018 Cisco and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''
Execution module to upgrade Cisco NX-OS Switches.
.. versionadded:: xxxx.xx.x
This module supports execution using a Proxy Minion or Native Minion:
1) Proxy Minion: Connect over SSH or NX-API HTTP(S).
See :mod:`salt.proxy.nxos <salt.proxy.nxos>` for proxy minion setup details.
2) Native Minion: Connect over NX-API Unix Domain Socket (UDS).
Install the minion inside the GuestShell running on the NX-OS device.
:maturity: new
:platform: nxos
:codeauthor: Michael G Wiebe
.. note::
To use this module over remote NX-API the feature must be enabled on the
NX-OS device by executing ``feature nxapi`` in configuration mode.
This is not required for NX-API over UDS.
Configuration example:
.. code-block:: bash
switch# conf t
switch(config)# feature nxapi
To check that NX-API is properly enabled, execute ``show nxapi``.
Output example:
.. code-block:: bash
switch# show nxapi
nxapi enabled
HTTPS Listen on port 443
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python stdlib
import logging
import re
import ast
import time
from salt.ext.six import string_types
# Import Salt libs
from salt.exceptions import (NxosError, CommandExecutionError)
from salt.ext.six.moves import range
__virtualname__ = 'nxos'
__virtual_aliases__ = ('nxos_upgrade',)
log = logging.getLogger(__name__)
def __virtual__():
return __virtualname__
def check_upgrade_impact(system_image, kickstart_image=None, issu=True, **kwargs):
'''
Display upgrade impact information without actually upgrading the device.
system_image (Mandatory Option)
Path on bootflash: to system image upgrade file.
kickstart_image
Path on bootflash: to kickstart image upgrade file.
(Not required if using combined system/kickstart image file)
Default: None
issu
When True: Attempt In Service Software Upgrade. (non-disruptive)
The upgrade will abort if issu is not possible.
When False: Force (disruptive) Upgrade/Downgrade.
Default: True
timeout
Timeout in seconds for long running 'install all' impact command.
Default: 900
error_pattern
Use the option to pass in a regular expression to search for in the
output of the 'install all impact' command that indicates an error
has occurred. This option is only used when proxy minion connection
type is ssh and otherwise ignored.
.. code-block:: bash
salt 'n9k' nxos.check_upgrade_impact system_image=nxos.9.2.1.bin
salt 'n7k' nxos.check_upgrade_impact system_image=n7000-s2-dk9.8.1.1.bin \\
kickstart_image=n7000-s2-kickstart.8.1.1.bin issu=False
'''
# Input Validation
if not isinstance(issu, bool):
return 'Input Error: The [issu] parameter must be either True or False'
si = system_image
ki = kickstart_image
dev = 'bootflash'
cmd = 'terminal dont-ask ; show install all impact'
if ki is not None:
cmd = cmd + ' kickstart {0}:{1} system {0}:{2}'.format(dev, ki, si)
else:
cmd = cmd + ' nxos {0}:{1}'.format(dev, si)
if issu and ki is None:
cmd = cmd + ' non-disruptive'
log.info("Check upgrade impact using command: '%s'", cmd)
kwargs.update({'timeout': kwargs.get('timeout', 900)})
error_pattern_list = ['Another install procedure may be in progress',
'Pre-upgrade check failed']
kwargs.update({'error_pattern': error_pattern_list})
# Execute Upgrade Impact Check
try:
impact_check = __salt__['nxos.sendline'](cmd, **kwargs)
except CommandExecutionError as e:
impact_check = ast.literal_eval(e.message)
return _parse_upgrade_data(impact_check)
def upgrade(system_image, kickstart_image=None, issu=True, **kwargs):
'''
Upgrade NX-OS switch.
system_image (Mandatory Option)
Path on bootflash: to system image upgrade file.
kickstart_image
Path on bootflash: to kickstart image upgrade file.
(Not required if using combined system/kickstart image file)
Default: None
issu
Set this option to True when an In Service Software Upgrade or
non-disruptive upgrade is required. The upgrade will abort if issu is
not possible.
Default: True
timeout
Timeout in seconds for long running 'install all' upgrade command.
Default: 900
error_pattern
Use the option to pass in a regular expression to search for in the
output of the 'install all upgrade command that indicates an error
has occurred. This option is only used when proxy minion connection
type is ssh and otherwise ignored.
.. code-block:: bash
salt 'n9k' nxos.upgrade system_image=nxos.9.2.1.bin
salt 'n7k' nxos.upgrade system_image=n7000-s2-dk9.8.1.1.bin \\
kickstart_image=n7000-s2-kickstart.8.1.1.bin issu=False
'''
# Input Validation
if not isinstance(issu, bool):
return 'Input Error: The [issu] parameter must be either True or False'
impact = None
upgrade = None
maxtry = 60
for attempt in range(1, maxtry):
# Gather impact data first. It's possible to loose upgrade data
# when the switch reloads or switches over to the inactive supervisor.
# The impact data will be used if data being collected during the
# upgrade is lost.
if impact is None:
log.info('Gathering impact data')
impact = check_upgrade_impact(system_image, kickstart_image,
issu, **kwargs)
if impact['installing']:
log.info('Another show impact in progress... wait and retry')
time.sleep(30)
continue
# If we are upgrading from a system running a separate system and
# kickstart image to a combined image or vice versa then the impact
# check will return a syntax error as it's not supported.
# Skip the impact check in this case and attempt the upgrade.
if impact['invalid_command']:
impact = False
continue
log.info('Impact data gathered:\n%s', impact)
# Check to see if conditions are sufficent to return the impact
# data and not proceed with the actual upgrade.
#
# Impact data indicates the upgrade or downgrade will fail
if impact['error_data']:
return impact
# Requested ISSU but ISSU is not possible
if issu and not impact['upgrade_non_disruptive']:
impact['error_data'] = impact['upgrade_data']
return impact
# Impact data indicates a failure and no module_data collected
if not impact['succeeded'] and not impact['module_data']:
impact['error_data'] = impact['upgrade_data']
return impact
# Impact data indicates switch already running desired image
if not impact['upgrade_required']:
impact['succeeded'] = True
return impact
# If we get here, impact data indicates upgrade is needed.
upgrade = _upgrade(system_image, kickstart_image, issu, **kwargs)
if upgrade['installing']:
log.info('Another install is in progress... wait and retry')
time.sleep(30)
continue
# If the issu option is False and this upgrade request includes a
# kickstart image then the 'force' option is used. This option is
# only available in certain image sets.
if upgrade['invalid_command']:
log_msg = 'The [issu] option was set to False for this upgrade.'
log_msg = log_msg + ' Attempt was made to ugrade using the force'
log_msg = log_msg + ' keyword which is not supported in this'
log_msg = log_msg + ' image. Set [issu=True] and re-try.'
upgrade['upgrade_data'] = log_msg
break
break
# Check for errors and return upgrade result:
if upgrade['backend_processing_error']:
# This means we received a backend processing error from the transport
# and lost the upgrade data. This also indicates that the upgrade
# is in progress so use the impact data for logging purposes.
impact['upgrade_in_progress'] = True
return impact
return upgrade
def _parse_upgrade_data(data):
'''
Helper method to parse upgrade data from the NX-OS device.
'''
upgrade_result = {}
upgrade_result['upgrade_data'] = None
upgrade_result['succeeded'] = False
upgrade_result['upgrade_required'] = False
upgrade_result['upgrade_non_disruptive'] = False
upgrade_result['upgrade_in_progress'] = False
upgrade_result['installing'] = False
upgrade_result['module_data'] = {}
upgrade_result['error_data'] = None
upgrade_result['backend_processing_error'] = False
upgrade_result['invalid_command'] = False
# Error handling
if isinstance(data, string_types) and re.search('Code: 500', data):
log.info('Detected backend processing error')
upgrade_result['error_data'] = data
upgrade_result['backend_processing_error'] = True
return upgrade_result
if isinstance(data, dict):
if 'code' in data and data['code'] == '400':
log.info('Detected client error')
upgrade_result['error_data'] = data['cli_error']
if re.search('install.*may be in progress', data['cli_error']):
log.info('Detected install in progress...')
upgrade_result['installing'] = True
if re.search('Invalid command', data['cli_error']):
log.info('Detected invalid command...')
upgrade_result['invalid_command'] = True
else:
# If we get here then it's likely we lost access to the device
# but the upgrade succeeded. We lost the actual upgrade data so
# set the flag such that impact data is used instead.
log.info('Probable backend processing error')
upgrade_result['backend_processing_error'] = True
return upgrade_result
# Get upgrade data for further parsing
# Case 1: Command terminal dont-ask returns empty {} that we don't need.
if isinstance(data, list) and len(data) == 2:
data = data[1]
# Case 2: Command terminal dont-ask does not get included.
if isinstance(data, list) and len(data) == 1:
data = data[0]
log.info('Parsing NX-OS upgrade data')
upgrade_result['upgrade_data'] = data
for line in data.split('\n'):
log.info('Processing line: (%s)', line)
# Check to see if upgrade is disruptive or non-disruptive
if re.search(r'non-disruptive', line):
log.info('Found non-disruptive line')
upgrade_result['upgrade_non_disruptive'] = True
# Example:
# Module Image Running-Version(pri:alt) New-Version Upg-Required
# 1 nxos 7.0(3)I7(5a) 7.0(3)I7(5a) no
# 1 bios v07.65(09/04/2018) v07.64(05/16/2018) no
mo = re.search(r'(\d+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(yes|no)', line)
if mo:
log.info('Matched Module Running/New Version Upg-Req Line')
bk = 'module_data' # base key
g1 = mo.group(1)
g2 = mo.group(2)
g3 = mo.group(3)
g4 = mo.group(4)
g5 = mo.group(5)
mk = 'module {0}:image {1}'.format(g1, g2) # module key
upgrade_result[bk][mk] = {}
upgrade_result[bk][mk]['running_version'] = g3
upgrade_result[bk][mk]['new_version'] = g4
if g5 == 'yes':
upgrade_result['upgrade_required'] = True
upgrade_result[bk][mk]['upgrade_required'] = True
continue
# The following lines indicate a successfull upgrade.
if re.search(r'Install has been successful', line):
log.info('Install successful line')
upgrade_result['succeeded'] = True
continue
if re.search(r'Finishing the upgrade, switch will reboot in', line):
log.info('Finishing upgrade line')
upgrade_result['upgrade_in_progress'] = True
continue
if re.search(r'Switch will be reloaded for disruptive upgrade', line):
log.info('Switch will be reloaded line')
upgrade_result['upgrade_in_progress'] = True
continue
if re.search(r'Switching over onto standby', line):
log.info('Switching over onto standby line')
upgrade_result['upgrade_in_progress'] = True
continue
return upgrade_result
|
saltstack/salt
|
salt/modules/nxos_upgrade.py
|
_parse_upgrade_data
|
python
|
def _parse_upgrade_data(data):
'''
Helper method to parse upgrade data from the NX-OS device.
'''
upgrade_result = {}
upgrade_result['upgrade_data'] = None
upgrade_result['succeeded'] = False
upgrade_result['upgrade_required'] = False
upgrade_result['upgrade_non_disruptive'] = False
upgrade_result['upgrade_in_progress'] = False
upgrade_result['installing'] = False
upgrade_result['module_data'] = {}
upgrade_result['error_data'] = None
upgrade_result['backend_processing_error'] = False
upgrade_result['invalid_command'] = False
# Error handling
if isinstance(data, string_types) and re.search('Code: 500', data):
log.info('Detected backend processing error')
upgrade_result['error_data'] = data
upgrade_result['backend_processing_error'] = True
return upgrade_result
if isinstance(data, dict):
if 'code' in data and data['code'] == '400':
log.info('Detected client error')
upgrade_result['error_data'] = data['cli_error']
if re.search('install.*may be in progress', data['cli_error']):
log.info('Detected install in progress...')
upgrade_result['installing'] = True
if re.search('Invalid command', data['cli_error']):
log.info('Detected invalid command...')
upgrade_result['invalid_command'] = True
else:
# If we get here then it's likely we lost access to the device
# but the upgrade succeeded. We lost the actual upgrade data so
# set the flag such that impact data is used instead.
log.info('Probable backend processing error')
upgrade_result['backend_processing_error'] = True
return upgrade_result
# Get upgrade data for further parsing
# Case 1: Command terminal dont-ask returns empty {} that we don't need.
if isinstance(data, list) and len(data) == 2:
data = data[1]
# Case 2: Command terminal dont-ask does not get included.
if isinstance(data, list) and len(data) == 1:
data = data[0]
log.info('Parsing NX-OS upgrade data')
upgrade_result['upgrade_data'] = data
for line in data.split('\n'):
log.info('Processing line: (%s)', line)
# Check to see if upgrade is disruptive or non-disruptive
if re.search(r'non-disruptive', line):
log.info('Found non-disruptive line')
upgrade_result['upgrade_non_disruptive'] = True
# Example:
# Module Image Running-Version(pri:alt) New-Version Upg-Required
# 1 nxos 7.0(3)I7(5a) 7.0(3)I7(5a) no
# 1 bios v07.65(09/04/2018) v07.64(05/16/2018) no
mo = re.search(r'(\d+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(yes|no)', line)
if mo:
log.info('Matched Module Running/New Version Upg-Req Line')
bk = 'module_data' # base key
g1 = mo.group(1)
g2 = mo.group(2)
g3 = mo.group(3)
g4 = mo.group(4)
g5 = mo.group(5)
mk = 'module {0}:image {1}'.format(g1, g2) # module key
upgrade_result[bk][mk] = {}
upgrade_result[bk][mk]['running_version'] = g3
upgrade_result[bk][mk]['new_version'] = g4
if g5 == 'yes':
upgrade_result['upgrade_required'] = True
upgrade_result[bk][mk]['upgrade_required'] = True
continue
# The following lines indicate a successfull upgrade.
if re.search(r'Install has been successful', line):
log.info('Install successful line')
upgrade_result['succeeded'] = True
continue
if re.search(r'Finishing the upgrade, switch will reboot in', line):
log.info('Finishing upgrade line')
upgrade_result['upgrade_in_progress'] = True
continue
if re.search(r'Switch will be reloaded for disruptive upgrade', line):
log.info('Switch will be reloaded line')
upgrade_result['upgrade_in_progress'] = True
continue
if re.search(r'Switching over onto standby', line):
log.info('Switching over onto standby line')
upgrade_result['upgrade_in_progress'] = True
continue
return upgrade_result
|
Helper method to parse upgrade data from the NX-OS device.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nxos_upgrade.py#L300-L405
| null |
# -*- coding: utf-8 -*-
# Copyright (c) 2018 Cisco and/or its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''
Execution module to upgrade Cisco NX-OS Switches.
.. versionadded:: xxxx.xx.x
This module supports execution using a Proxy Minion or Native Minion:
1) Proxy Minion: Connect over SSH or NX-API HTTP(S).
See :mod:`salt.proxy.nxos <salt.proxy.nxos>` for proxy minion setup details.
2) Native Minion: Connect over NX-API Unix Domain Socket (UDS).
Install the minion inside the GuestShell running on the NX-OS device.
:maturity: new
:platform: nxos
:codeauthor: Michael G Wiebe
.. note::
To use this module over remote NX-API the feature must be enabled on the
NX-OS device by executing ``feature nxapi`` in configuration mode.
This is not required for NX-API over UDS.
Configuration example:
.. code-block:: bash
switch# conf t
switch(config)# feature nxapi
To check that NX-API is properly enabled, execute ``show nxapi``.
Output example:
.. code-block:: bash
switch# show nxapi
nxapi enabled
HTTPS Listen on port 443
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python stdlib
import logging
import re
import ast
import time
from salt.ext.six import string_types
# Import Salt libs
from salt.exceptions import (NxosError, CommandExecutionError)
from salt.ext.six.moves import range
__virtualname__ = 'nxos'
__virtual_aliases__ = ('nxos_upgrade',)
log = logging.getLogger(__name__)
def __virtual__():
return __virtualname__
def check_upgrade_impact(system_image, kickstart_image=None, issu=True, **kwargs):
'''
Display upgrade impact information without actually upgrading the device.
system_image (Mandatory Option)
Path on bootflash: to system image upgrade file.
kickstart_image
Path on bootflash: to kickstart image upgrade file.
(Not required if using combined system/kickstart image file)
Default: None
issu
When True: Attempt In Service Software Upgrade. (non-disruptive)
The upgrade will abort if issu is not possible.
When False: Force (disruptive) Upgrade/Downgrade.
Default: True
timeout
Timeout in seconds for long running 'install all' impact command.
Default: 900
error_pattern
Use the option to pass in a regular expression to search for in the
output of the 'install all impact' command that indicates an error
has occurred. This option is only used when proxy minion connection
type is ssh and otherwise ignored.
.. code-block:: bash
salt 'n9k' nxos.check_upgrade_impact system_image=nxos.9.2.1.bin
salt 'n7k' nxos.check_upgrade_impact system_image=n7000-s2-dk9.8.1.1.bin \\
kickstart_image=n7000-s2-kickstart.8.1.1.bin issu=False
'''
# Input Validation
if not isinstance(issu, bool):
return 'Input Error: The [issu] parameter must be either True or False'
si = system_image
ki = kickstart_image
dev = 'bootflash'
cmd = 'terminal dont-ask ; show install all impact'
if ki is not None:
cmd = cmd + ' kickstart {0}:{1} system {0}:{2}'.format(dev, ki, si)
else:
cmd = cmd + ' nxos {0}:{1}'.format(dev, si)
if issu and ki is None:
cmd = cmd + ' non-disruptive'
log.info("Check upgrade impact using command: '%s'", cmd)
kwargs.update({'timeout': kwargs.get('timeout', 900)})
error_pattern_list = ['Another install procedure may be in progress',
'Pre-upgrade check failed']
kwargs.update({'error_pattern': error_pattern_list})
# Execute Upgrade Impact Check
try:
impact_check = __salt__['nxos.sendline'](cmd, **kwargs)
except CommandExecutionError as e:
impact_check = ast.literal_eval(e.message)
return _parse_upgrade_data(impact_check)
def upgrade(system_image, kickstart_image=None, issu=True, **kwargs):
'''
Upgrade NX-OS switch.
system_image (Mandatory Option)
Path on bootflash: to system image upgrade file.
kickstart_image
Path on bootflash: to kickstart image upgrade file.
(Not required if using combined system/kickstart image file)
Default: None
issu
Set this option to True when an In Service Software Upgrade or
non-disruptive upgrade is required. The upgrade will abort if issu is
not possible.
Default: True
timeout
Timeout in seconds for long running 'install all' upgrade command.
Default: 900
error_pattern
Use the option to pass in a regular expression to search for in the
output of the 'install all upgrade command that indicates an error
has occurred. This option is only used when proxy minion connection
type is ssh and otherwise ignored.
.. code-block:: bash
salt 'n9k' nxos.upgrade system_image=nxos.9.2.1.bin
salt 'n7k' nxos.upgrade system_image=n7000-s2-dk9.8.1.1.bin \\
kickstart_image=n7000-s2-kickstart.8.1.1.bin issu=False
'''
# Input Validation
if not isinstance(issu, bool):
return 'Input Error: The [issu] parameter must be either True or False'
impact = None
upgrade = None
maxtry = 60
for attempt in range(1, maxtry):
# Gather impact data first. It's possible to loose upgrade data
# when the switch reloads or switches over to the inactive supervisor.
# The impact data will be used if data being collected during the
# upgrade is lost.
if impact is None:
log.info('Gathering impact data')
impact = check_upgrade_impact(system_image, kickstart_image,
issu, **kwargs)
if impact['installing']:
log.info('Another show impact in progress... wait and retry')
time.sleep(30)
continue
# If we are upgrading from a system running a separate system and
# kickstart image to a combined image or vice versa then the impact
# check will return a syntax error as it's not supported.
# Skip the impact check in this case and attempt the upgrade.
if impact['invalid_command']:
impact = False
continue
log.info('Impact data gathered:\n%s', impact)
# Check to see if conditions are sufficent to return the impact
# data and not proceed with the actual upgrade.
#
# Impact data indicates the upgrade or downgrade will fail
if impact['error_data']:
return impact
# Requested ISSU but ISSU is not possible
if issu and not impact['upgrade_non_disruptive']:
impact['error_data'] = impact['upgrade_data']
return impact
# Impact data indicates a failure and no module_data collected
if not impact['succeeded'] and not impact['module_data']:
impact['error_data'] = impact['upgrade_data']
return impact
# Impact data indicates switch already running desired image
if not impact['upgrade_required']:
impact['succeeded'] = True
return impact
# If we get here, impact data indicates upgrade is needed.
upgrade = _upgrade(system_image, kickstart_image, issu, **kwargs)
if upgrade['installing']:
log.info('Another install is in progress... wait and retry')
time.sleep(30)
continue
# If the issu option is False and this upgrade request includes a
# kickstart image then the 'force' option is used. This option is
# only available in certain image sets.
if upgrade['invalid_command']:
log_msg = 'The [issu] option was set to False for this upgrade.'
log_msg = log_msg + ' Attempt was made to ugrade using the force'
log_msg = log_msg + ' keyword which is not supported in this'
log_msg = log_msg + ' image. Set [issu=True] and re-try.'
upgrade['upgrade_data'] = log_msg
break
break
# Check for errors and return upgrade result:
if upgrade['backend_processing_error']:
# This means we received a backend processing error from the transport
# and lost the upgrade data. This also indicates that the upgrade
# is in progress so use the impact data for logging purposes.
impact['upgrade_in_progress'] = True
return impact
return upgrade
def _upgrade(system_image, kickstart_image, issu, **kwargs):
'''
Helper method that does the heavy lifting for upgrades.
'''
si = system_image
ki = kickstart_image
dev = 'bootflash'
cmd = 'terminal dont-ask ; install all'
if ki is None:
logmsg = 'Upgrading device using combined system/kickstart image.'
logmsg += '\nSystem Image: {}'.format(si)
cmd = cmd + ' nxos {0}:{1}'.format(dev, si)
if issu:
cmd = cmd + ' non-disruptive'
else:
logmsg = 'Upgrading device using separate system/kickstart images.'
logmsg += '\nSystem Image: {}'.format(si)
logmsg += '\nKickstart Image: {}'.format(ki)
if not issu:
log.info('Attempting upgrade using force option')
cmd = cmd + ' force'
cmd = cmd + ' kickstart {0}:{1} system {0}:{2}'.format(dev, ki, si)
if issu:
logmsg += '\nIn Service Software Upgrade/Downgrade (non-disruptive) requested.'
else:
logmsg += '\nDisruptive Upgrade/Downgrade requested.'
log.info(logmsg)
log.info("Begin upgrade using command: '%s'", cmd)
kwargs.update({'timeout': kwargs.get('timeout', 900)})
error_pattern_list = ['Another install procedure may be in progress']
kwargs.update({'error_pattern': error_pattern_list})
# Begin Actual Upgrade
try:
upgrade_result = __salt__['nxos.sendline'](cmd, **kwargs)
except CommandExecutionError as e:
upgrade_result = ast.literal_eval(e.message)
except NxosError as e:
if re.search('Code: 500', e.message):
upgrade_result = e.message
else:
upgrade_result = ast.literal_eval(e.message)
return _parse_upgrade_data(upgrade_result)
|
saltstack/salt
|
salt/modules/dockercompose.py
|
__standardize_result
|
python
|
def __standardize_result(status, message, data=None, debug_msg=None):
'''
Standardizes all responses
:param status:
:param message:
:param data:
:param debug_msg:
:return:
'''
result = {
'status': status,
'message': message
}
if data is not None:
result['return'] = data
if debug_msg is not None and debug:
result['debug'] = debug_msg
return result
|
Standardizes all responses
:param status:
:param message:
:param data:
:param debug_msg:
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockercompose.py#L160-L181
| null |
# -*- coding: utf-8 -*-
'''
Module to import docker-compose via saltstack
.. versionadded:: 2016.3.0
:maintainer: Jean Praloran <jeanpralo@gmail.com>
:maturity: new
:depends: docker-compose>=1.5
:platform: all
Introduction
------------
This module allows one to deal with docker-compose file in a directory.
This is a first version only, the following commands are missing at the moment
but will be built later on if the community is interested in this module:
- run
- logs
- port
- scale
Installation Prerequisites
--------------------------
This execution module requires at least version 1.4.0 of both docker-compose_ and
Docker_. docker-compose can easily be installed using :py:func:`pip.install
<salt.modules.pip.install>`:
.. code-block:: bash
salt myminion pip.install docker-compose>=1.5.0
.. _docker-compose: https://pypi.python.org/pypi/docker-compose
.. _Docker: https://www.docker.com/
How to use this module?
-----------------------
In order to use the module if you have no docker-compose file on the server you
can issue the command create, it takes two arguments the path where the
docker-compose.yml will be stored and the content of this latter:
.. code-block:: text
# salt-call -l debug dockercompose.create /tmp/toto '
database:
image: mongo:3.0
command: mongod --smallfiles --quiet --logpath=/dev/null
'
Then you can execute a list of method defined at the bottom with at least one
argument (the path where the docker-compose.yml will be read) and an optional
python list which corresponds to the services names:
.. code-block:: bash
# salt-call -l debug dockercompose.up /tmp/toto
# salt-call -l debug dockercompose.restart /tmp/toto '[database]'
# salt-call -l debug dockercompose.stop /tmp/toto
# salt-call -l debug dockercompose.rm /tmp/toto
Docker-compose method supported
-------------------------------
- up
- restart
- stop
- start
- pause
- unpause
- kill
- rm
- ps
- pull
- build
Functions
---------
- docker-compose.yml management
- :py:func:`dockercompose.create <salt.modules.dockercompose.create>`
- :py:func:`dockercompose.get <salt.modules.dockercompose.get>`
- Manage containers
- :py:func:`dockercompose.restart <salt.modules.dockercompose.restart>`
- :py:func:`dockercompose.stop <salt.modules.dockercompose.stop>`
- :py:func:`dockercompose.pause <salt.modules.dockercompose.pause>`
- :py:func:`dockercompose.unpause <salt.modules.dockercompose.unpause>`
- :py:func:`dockercompose.start <salt.modules.dockercompose.start>`
- :py:func:`dockercompose.kill <salt.modules.dockercompose.kill>`
- :py:func:`dockercompose.rm <salt.modules.dockercompose.rm>`
- :py:func:`dockercompose.up <salt.modules.dockercompose.up>`
- Manage containers image:
- :py:func:`dockercompose.pull <salt.modules.dockercompose.pull>`
- :py:func:`dockercompose.build <salt.modules.dockercompose.build>`
- Gather information about containers:
- :py:func:`dockercompose.ps <salt.modules.dockercompose.ps>`
- Manage service definitions:
- :py:func:`dockercompose.service_create <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_upsert <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_remove <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_set_tag <salt.modules.dockercompose.ps>`
Detailed Function Documentation
-------------------------------
'''
from __future__ import absolute_import, print_function, unicode_literals
import inspect
import logging
import os
import re
import salt.utils.files
import salt.utils.stringutils
from salt.ext import six
from operator import attrgetter
from salt.serializers import json
from salt.utils import yaml
try:
import compose
from compose.cli.command import get_project
from compose.service import ConvergenceStrategy
HAS_DOCKERCOMPOSE = True
except ImportError:
HAS_DOCKERCOMPOSE = False
try:
from compose.project import OneOffFilter
USE_FILTERCLASS = True
except ImportError:
USE_FILTERCLASS = False
MIN_DOCKERCOMPOSE = (1, 5, 0)
VERSION_RE = r'([\d.]+)'
log = logging.getLogger(__name__)
debug = False
__virtualname__ = 'dockercompose'
DEFAULT_DC_FILENAMES = ('docker-compose.yml', 'docker-compose.yaml')
def __virtual__():
if HAS_DOCKERCOMPOSE:
match = re.match(VERSION_RE, six.text_type(compose.__version__))
if match:
version = tuple([int(x) for x in match.group(1).split('.')])
if version >= MIN_DOCKERCOMPOSE:
return __virtualname__
return (False, 'The dockercompose execution module not loaded: '
'compose python library not available.')
def __get_docker_file_path(path):
'''
Determines the filepath to use
:param path:
:return:
'''
if os.path.isfile(path):
return path
for dc_filename in DEFAULT_DC_FILENAMES:
file_path = os.path.join(path, dc_filename)
if os.path.isfile(file_path):
return file_path
# implicitly return None
def __read_docker_compose_file(file_path):
'''
Read the compose file if it exists in the directory
:param file_path:
:return:
'''
if not os.path.isfile(file_path):
return __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
file_name = os.path.basename(file_path)
result = {file_name: ''}
for line in fl:
result[file_name] += salt.utils.stringutils.to_unicode(line)
except EnvironmentError:
return __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
return __standardize_result(True,
'Reading content of {0}'.format(file_path),
result, None)
def __load_docker_compose(path):
'''
Read the compose file and load its' contents
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return None, __standardize_result(False, msg,
None, None)
if not os.path.isfile(file_path):
return None, __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
loaded = yaml.load(fl)
except EnvironmentError:
return None, __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(file_path, yerr)
return None, __standardize_result(False, msg,
None, None)
if not loaded:
msg = 'Got empty compose file at {0}'.format(file_path)
return None, __standardize_result(False, msg,
None, None)
if 'services' not in loaded:
loaded['services'] = {}
result = {
'compose_content': loaded,
'file_name': os.path.basename(file_path)
}
return result, None
def __dump_docker_compose(path, content, already_existed):
'''
Dumps
:param path:
:param content: the not-yet dumped content
:return:
'''
try:
dumped = yaml.safe_dump(content, indent=2, default_flow_style=False)
return __write_docker_compose(path, dumped, already_existed)
except TypeError as t_err:
msg = 'Could not dump {0} {1}'.format(content, t_err)
return __standardize_result(False, msg,
None, None)
def __write_docker_compose(path, docker_compose, already_existed):
'''
Write docker-compose to a path
in order to use it with docker-compose ( config check )
:param path:
docker_compose
contains the docker-compose file
:return:
'''
if path.lower().endswith(('.yml', '.yaml')):
file_path = path
dir_name = os.path.dirname(path)
else:
dir_name = path
file_path = os.path.join(dir_name, DEFAULT_DC_FILENAMES[0])
if os.path.isdir(dir_name) is False:
os.mkdir(dir_name)
try:
with salt.utils.files.fopen(file_path, 'w') as fl:
fl.write(salt.utils.stringutils.to_str(docker_compose))
except EnvironmentError:
return __standardize_result(False,
'Could not write {0}'.format(file_path),
None, None)
project = __load_project_from_file_path(file_path)
if isinstance(project, dict):
if not already_existed:
os.remove(file_path)
return project
return file_path
def __load_project(path):
'''
Load a docker-compose project from path
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return __standardize_result(False,
msg,
None, None)
return __load_project_from_file_path(file_path)
def __load_project_from_file_path(file_path):
'''
Load a docker-compose project from file path
:param path:
:return:
'''
try:
project = get_project(project_dir=os.path.dirname(file_path),
config_path=[os.path.basename(file_path)])
except Exception as inst:
return __handle_except(inst)
return project
def __load_compose_definitions(path, definition):
'''
Will load the compose file located at path
Then determines the format/contents of the sent definition
err or results are only set if there were any
:param path:
:param definition:
:return tuple(compose_result, loaded_definition, err):
'''
compose_result, err = __load_docker_compose(path)
if err:
return None, None, err
if isinstance(definition, dict):
return compose_result, definition, None
elif definition.strip().startswith('{'):
try:
loaded_definition = json.deserialize(definition)
except json.DeserializationError as jerr:
msg = 'Could not parse {0} {1}'.format(definition, jerr)
return None, None, __standardize_result(False, msg,
None, None)
else:
try:
loaded_definition = yaml.load(definition)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(definition, yerr)
return None, None, __standardize_result(False, msg,
None, None)
return compose_result, loaded_definition, None
def __dump_compose_file(path, compose_result, success_msg, already_existed):
'''
Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return:
'''
ret = __dump_docker_compose(path,
compose_result['compose_content'],
already_existed)
if isinstance(ret, dict):
return ret
return __standardize_result(True, success_msg,
compose_result['compose_content'], None)
def __handle_except(inst):
'''
Handle exception and return a standard result
:param inst:
:return:
'''
return __standardize_result(False,
'Docker-compose command {0} failed'.
format(inspect.stack()[1][3]),
'{0}'.format(inst), None)
def _get_convergence_plans(project, service_names):
'''
Get action executed for each container
:param project:
:param service_names:
:return:
'''
ret = {}
plans = project._get_convergence_plans(project.get_services(service_names),
ConvergenceStrategy.changed)
for cont in plans:
(action, container) = plans[cont]
if action == 'create':
ret[cont] = 'Creating container'
elif action == 'recreate':
ret[cont] = 'Re-creating container'
elif action == 'start':
ret[cont] = 'Starting container'
elif action == 'noop':
ret[cont] = 'Container is up to date'
return ret
def get(path):
'''
Get the content of the docker-compose file into a directory
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.get /path/where/docker-compose/stored
'''
file_path = __get_docker_file_path(path)
if file_path is None:
return __standardize_result(False,
'Path {} is not present'.format(path),
None, None)
salt_result = __read_docker_compose_file(file_path)
if not salt_result['status']:
return salt_result
project = __load_project(path)
if isinstance(project, dict):
salt_result['return']['valid'] = False
else:
salt_result['return']['valid'] = True
return salt_result
def create(path, docker_compose):
'''
Create and validate a docker-compose file into a directory
path
Path where the docker-compose file will be stored on the server
docker_compose
docker_compose file
CLI Example:
.. code-block:: bash
salt myminion dockercompose.create /path/where/docker-compose/stored content
'''
if docker_compose:
ret = __write_docker_compose(path,
docker_compose,
already_existed=False)
if isinstance(ret, dict):
return ret
else:
return __standardize_result(False,
'Creating a docker-compose project failed, you must send a valid docker-compose file',
None, None)
return __standardize_result(True,
'Successfully created the docker-compose file',
{'compose.base_dir': path},
None)
def pull(path, service_names=None):
'''
Pull image for containers in the docker-compose file, service_names is a
python list, if omitted pull all images
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pull /path/where/docker-compose/stored
salt myminion dockercompose.pull /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.pull(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pulling containers images via docker-compose succeeded',
None, None)
def build(path, service_names=None):
'''
Build image for containers in the docker-compose file, service_names is a
python list, if omitted build images for all containers. Please note
that at the moment the module does not allow you to upload your Dockerfile,
nor any other file you could need with your docker-compose.yml, you will
have to make sure the files you need are actually in the directory specified
in the `build` keyword
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.build /path/where/docker-compose/stored
salt myminion dockercompose.build /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.build(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Building containers images via docker-compose succeeded',
None, None)
def restart(path, service_names=None):
'''
Restart container(s) in the docker-compose file, service_names is a python
list, if omitted restart all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will restart only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.restart /path/where/docker-compose/stored
salt myminion dockercompose.restart /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.restart(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'restarted'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Restarting containers via docker-compose', result, debug_ret)
def stop(path, service_names=None):
'''
Stop running containers in the docker-compose file, service_names is a python
list, if omitted stop all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will stop only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.stop /path/where/docker-compose/stored
salt myminion dockercompose.stop /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
def pause(path, service_names=None):
'''
Pause running containers in the docker-compose file, service_names is a python
list, if omitted pause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.pause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'paused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pausing containers via docker-compose', result, debug_ret)
def unpause(path, service_names=None):
'''
Un-Pause containers in the docker-compose file, service_names is a python
list, if omitted unpause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will un-pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.unpause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'unpaused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Un-Pausing containers via docker-compose', result, debug_ret)
def start(path, service_names=None):
'''
Start containers in the docker-compose file, service_names is a python
list, if omitted start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.start /path/where/docker-compose/stored
salt myminion dockercompose.start /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.start(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'started'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Starting containers via docker-compose', result, debug_ret)
def kill(path, service_names=None):
'''
Kill containers in the docker-compose file, service_names is a python
list, if omitted kill all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will kill only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.kill /path/where/docker-compose/stored
salt myminion dockercompose.kill /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.kill(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'killed'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Killing containers via docker-compose', result, debug_ret)
def rm(path, service_names=None):
'''
Remove stopped containers in the docker-compose file, service_names is a python
list, if omitted remove all stopped containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will remove only the specified stopped services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.rm /path/where/docker-compose/stored
salt myminion dockercompose.rm /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.remove_stopped(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Removing stopped containers via docker-compose', None, None)
def ps(path):
'''
List all running containers and report some information about them
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.ps /path/where/docker-compose/stored
'''
project = __load_project(path)
result = {}
if isinstance(project, dict):
return project
else:
if USE_FILTERCLASS:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, OneOffFilter.only),
key=attrgetter('name'))
else:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, one_off=True),
key=attrgetter('name'))
for container in containers:
command = container.human_readable_command
if len(command) > 30:
command = '{0} ...'.format(command[:26])
result[container.name] = {
'id': container.id,
'name': container.name,
'command': command,
'state': container.human_readable_state,
'ports': container.human_readable_ports,
}
return __standardize_result(True, 'Listing docker-compose containers', result, None)
def up(path, service_names=None):
'''
Create and start containers defined in the docker-compose.yml file
located in path, service_names is a python list, if omitted create and
start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will create and start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.up /path/where/docker-compose/stored
salt myminion dockercompose.up /path/where/docker-compose/stored '[janus]'
'''
debug_ret = {}
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
result = _get_convergence_plans(project, service_names)
ret = project.up(service_names)
if debug:
for container in ret:
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Adding containers via docker-compose', result, debug_ret)
def service_create(path, service_name, definition):
'''
Create the definition of a docker-compose service
This fails when the service already exists
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service {0} created'.format(service_name),
already_existed=True)
def service_upsert(path, service_name, definition):
'''
Create or update the definition of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_upsert /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service definition for {0} is set'.format(service_name),
already_existed=True)
def service_remove(path, service_name):
'''
Remove the definition of a docker-compose service
This does not rm the container
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_remove /path/where/docker-compose/stored service_name
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
del services[service_name]
return __dump_compose_file(path, compose_result,
'Service {0} is removed from {1}'.format(service_name, path),
already_existed=True)
def service_set_tag(path, service_name, tag):
'''
Change the tag of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
tag
Name of the tag (often used as version) that the service image should have
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name tag
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
if 'image' not in services[service_name]:
return __standardize_result(False,
'Service {0} did not contain the variable "image"'.format(service_name),
None, None)
image = services[service_name]['image'].split(':')[0]
services[service_name]['image'] = '{0}:{1}'.format(image, tag)
return __dump_compose_file(path, compose_result,
'Service {0} is set to tag "{1}"'.format(service_name, tag),
already_existed=True)
|
saltstack/salt
|
salt/modules/dockercompose.py
|
__get_docker_file_path
|
python
|
def __get_docker_file_path(path):
'''
Determines the filepath to use
:param path:
:return:
'''
if os.path.isfile(path):
return path
for dc_filename in DEFAULT_DC_FILENAMES:
file_path = os.path.join(path, dc_filename)
if os.path.isfile(file_path):
return file_path
|
Determines the filepath to use
:param path:
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockercompose.py#L184-L196
| null |
# -*- coding: utf-8 -*-
'''
Module to import docker-compose via saltstack
.. versionadded:: 2016.3.0
:maintainer: Jean Praloran <jeanpralo@gmail.com>
:maturity: new
:depends: docker-compose>=1.5
:platform: all
Introduction
------------
This module allows one to deal with docker-compose file in a directory.
This is a first version only, the following commands are missing at the moment
but will be built later on if the community is interested in this module:
- run
- logs
- port
- scale
Installation Prerequisites
--------------------------
This execution module requires at least version 1.4.0 of both docker-compose_ and
Docker_. docker-compose can easily be installed using :py:func:`pip.install
<salt.modules.pip.install>`:
.. code-block:: bash
salt myminion pip.install docker-compose>=1.5.0
.. _docker-compose: https://pypi.python.org/pypi/docker-compose
.. _Docker: https://www.docker.com/
How to use this module?
-----------------------
In order to use the module if you have no docker-compose file on the server you
can issue the command create, it takes two arguments the path where the
docker-compose.yml will be stored and the content of this latter:
.. code-block:: text
# salt-call -l debug dockercompose.create /tmp/toto '
database:
image: mongo:3.0
command: mongod --smallfiles --quiet --logpath=/dev/null
'
Then you can execute a list of method defined at the bottom with at least one
argument (the path where the docker-compose.yml will be read) and an optional
python list which corresponds to the services names:
.. code-block:: bash
# salt-call -l debug dockercompose.up /tmp/toto
# salt-call -l debug dockercompose.restart /tmp/toto '[database]'
# salt-call -l debug dockercompose.stop /tmp/toto
# salt-call -l debug dockercompose.rm /tmp/toto
Docker-compose method supported
-------------------------------
- up
- restart
- stop
- start
- pause
- unpause
- kill
- rm
- ps
- pull
- build
Functions
---------
- docker-compose.yml management
- :py:func:`dockercompose.create <salt.modules.dockercompose.create>`
- :py:func:`dockercompose.get <salt.modules.dockercompose.get>`
- Manage containers
- :py:func:`dockercompose.restart <salt.modules.dockercompose.restart>`
- :py:func:`dockercompose.stop <salt.modules.dockercompose.stop>`
- :py:func:`dockercompose.pause <salt.modules.dockercompose.pause>`
- :py:func:`dockercompose.unpause <salt.modules.dockercompose.unpause>`
- :py:func:`dockercompose.start <salt.modules.dockercompose.start>`
- :py:func:`dockercompose.kill <salt.modules.dockercompose.kill>`
- :py:func:`dockercompose.rm <salt.modules.dockercompose.rm>`
- :py:func:`dockercompose.up <salt.modules.dockercompose.up>`
- Manage containers image:
- :py:func:`dockercompose.pull <salt.modules.dockercompose.pull>`
- :py:func:`dockercompose.build <salt.modules.dockercompose.build>`
- Gather information about containers:
- :py:func:`dockercompose.ps <salt.modules.dockercompose.ps>`
- Manage service definitions:
- :py:func:`dockercompose.service_create <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_upsert <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_remove <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_set_tag <salt.modules.dockercompose.ps>`
Detailed Function Documentation
-------------------------------
'''
from __future__ import absolute_import, print_function, unicode_literals
import inspect
import logging
import os
import re
import salt.utils.files
import salt.utils.stringutils
from salt.ext import six
from operator import attrgetter
from salt.serializers import json
from salt.utils import yaml
try:
import compose
from compose.cli.command import get_project
from compose.service import ConvergenceStrategy
HAS_DOCKERCOMPOSE = True
except ImportError:
HAS_DOCKERCOMPOSE = False
try:
from compose.project import OneOffFilter
USE_FILTERCLASS = True
except ImportError:
USE_FILTERCLASS = False
MIN_DOCKERCOMPOSE = (1, 5, 0)
VERSION_RE = r'([\d.]+)'
log = logging.getLogger(__name__)
debug = False
__virtualname__ = 'dockercompose'
DEFAULT_DC_FILENAMES = ('docker-compose.yml', 'docker-compose.yaml')
def __virtual__():
if HAS_DOCKERCOMPOSE:
match = re.match(VERSION_RE, six.text_type(compose.__version__))
if match:
version = tuple([int(x) for x in match.group(1).split('.')])
if version >= MIN_DOCKERCOMPOSE:
return __virtualname__
return (False, 'The dockercompose execution module not loaded: '
'compose python library not available.')
def __standardize_result(status, message, data=None, debug_msg=None):
'''
Standardizes all responses
:param status:
:param message:
:param data:
:param debug_msg:
:return:
'''
result = {
'status': status,
'message': message
}
if data is not None:
result['return'] = data
if debug_msg is not None and debug:
result['debug'] = debug_msg
return result
# implicitly return None
def __read_docker_compose_file(file_path):
'''
Read the compose file if it exists in the directory
:param file_path:
:return:
'''
if not os.path.isfile(file_path):
return __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
file_name = os.path.basename(file_path)
result = {file_name: ''}
for line in fl:
result[file_name] += salt.utils.stringutils.to_unicode(line)
except EnvironmentError:
return __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
return __standardize_result(True,
'Reading content of {0}'.format(file_path),
result, None)
def __load_docker_compose(path):
'''
Read the compose file and load its' contents
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return None, __standardize_result(False, msg,
None, None)
if not os.path.isfile(file_path):
return None, __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
loaded = yaml.load(fl)
except EnvironmentError:
return None, __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(file_path, yerr)
return None, __standardize_result(False, msg,
None, None)
if not loaded:
msg = 'Got empty compose file at {0}'.format(file_path)
return None, __standardize_result(False, msg,
None, None)
if 'services' not in loaded:
loaded['services'] = {}
result = {
'compose_content': loaded,
'file_name': os.path.basename(file_path)
}
return result, None
def __dump_docker_compose(path, content, already_existed):
'''
Dumps
:param path:
:param content: the not-yet dumped content
:return:
'''
try:
dumped = yaml.safe_dump(content, indent=2, default_flow_style=False)
return __write_docker_compose(path, dumped, already_existed)
except TypeError as t_err:
msg = 'Could not dump {0} {1}'.format(content, t_err)
return __standardize_result(False, msg,
None, None)
def __write_docker_compose(path, docker_compose, already_existed):
'''
Write docker-compose to a path
in order to use it with docker-compose ( config check )
:param path:
docker_compose
contains the docker-compose file
:return:
'''
if path.lower().endswith(('.yml', '.yaml')):
file_path = path
dir_name = os.path.dirname(path)
else:
dir_name = path
file_path = os.path.join(dir_name, DEFAULT_DC_FILENAMES[0])
if os.path.isdir(dir_name) is False:
os.mkdir(dir_name)
try:
with salt.utils.files.fopen(file_path, 'w') as fl:
fl.write(salt.utils.stringutils.to_str(docker_compose))
except EnvironmentError:
return __standardize_result(False,
'Could not write {0}'.format(file_path),
None, None)
project = __load_project_from_file_path(file_path)
if isinstance(project, dict):
if not already_existed:
os.remove(file_path)
return project
return file_path
def __load_project(path):
'''
Load a docker-compose project from path
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return __standardize_result(False,
msg,
None, None)
return __load_project_from_file_path(file_path)
def __load_project_from_file_path(file_path):
'''
Load a docker-compose project from file path
:param path:
:return:
'''
try:
project = get_project(project_dir=os.path.dirname(file_path),
config_path=[os.path.basename(file_path)])
except Exception as inst:
return __handle_except(inst)
return project
def __load_compose_definitions(path, definition):
'''
Will load the compose file located at path
Then determines the format/contents of the sent definition
err or results are only set if there were any
:param path:
:param definition:
:return tuple(compose_result, loaded_definition, err):
'''
compose_result, err = __load_docker_compose(path)
if err:
return None, None, err
if isinstance(definition, dict):
return compose_result, definition, None
elif definition.strip().startswith('{'):
try:
loaded_definition = json.deserialize(definition)
except json.DeserializationError as jerr:
msg = 'Could not parse {0} {1}'.format(definition, jerr)
return None, None, __standardize_result(False, msg,
None, None)
else:
try:
loaded_definition = yaml.load(definition)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(definition, yerr)
return None, None, __standardize_result(False, msg,
None, None)
return compose_result, loaded_definition, None
def __dump_compose_file(path, compose_result, success_msg, already_existed):
'''
Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return:
'''
ret = __dump_docker_compose(path,
compose_result['compose_content'],
already_existed)
if isinstance(ret, dict):
return ret
return __standardize_result(True, success_msg,
compose_result['compose_content'], None)
def __handle_except(inst):
'''
Handle exception and return a standard result
:param inst:
:return:
'''
return __standardize_result(False,
'Docker-compose command {0} failed'.
format(inspect.stack()[1][3]),
'{0}'.format(inst), None)
def _get_convergence_plans(project, service_names):
'''
Get action executed for each container
:param project:
:param service_names:
:return:
'''
ret = {}
plans = project._get_convergence_plans(project.get_services(service_names),
ConvergenceStrategy.changed)
for cont in plans:
(action, container) = plans[cont]
if action == 'create':
ret[cont] = 'Creating container'
elif action == 'recreate':
ret[cont] = 'Re-creating container'
elif action == 'start':
ret[cont] = 'Starting container'
elif action == 'noop':
ret[cont] = 'Container is up to date'
return ret
def get(path):
'''
Get the content of the docker-compose file into a directory
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.get /path/where/docker-compose/stored
'''
file_path = __get_docker_file_path(path)
if file_path is None:
return __standardize_result(False,
'Path {} is not present'.format(path),
None, None)
salt_result = __read_docker_compose_file(file_path)
if not salt_result['status']:
return salt_result
project = __load_project(path)
if isinstance(project, dict):
salt_result['return']['valid'] = False
else:
salt_result['return']['valid'] = True
return salt_result
def create(path, docker_compose):
'''
Create and validate a docker-compose file into a directory
path
Path where the docker-compose file will be stored on the server
docker_compose
docker_compose file
CLI Example:
.. code-block:: bash
salt myminion dockercompose.create /path/where/docker-compose/stored content
'''
if docker_compose:
ret = __write_docker_compose(path,
docker_compose,
already_existed=False)
if isinstance(ret, dict):
return ret
else:
return __standardize_result(False,
'Creating a docker-compose project failed, you must send a valid docker-compose file',
None, None)
return __standardize_result(True,
'Successfully created the docker-compose file',
{'compose.base_dir': path},
None)
def pull(path, service_names=None):
'''
Pull image for containers in the docker-compose file, service_names is a
python list, if omitted pull all images
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pull /path/where/docker-compose/stored
salt myminion dockercompose.pull /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.pull(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pulling containers images via docker-compose succeeded',
None, None)
def build(path, service_names=None):
'''
Build image for containers in the docker-compose file, service_names is a
python list, if omitted build images for all containers. Please note
that at the moment the module does not allow you to upload your Dockerfile,
nor any other file you could need with your docker-compose.yml, you will
have to make sure the files you need are actually in the directory specified
in the `build` keyword
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.build /path/where/docker-compose/stored
salt myminion dockercompose.build /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.build(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Building containers images via docker-compose succeeded',
None, None)
def restart(path, service_names=None):
'''
Restart container(s) in the docker-compose file, service_names is a python
list, if omitted restart all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will restart only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.restart /path/where/docker-compose/stored
salt myminion dockercompose.restart /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.restart(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'restarted'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Restarting containers via docker-compose', result, debug_ret)
def stop(path, service_names=None):
'''
Stop running containers in the docker-compose file, service_names is a python
list, if omitted stop all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will stop only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.stop /path/where/docker-compose/stored
salt myminion dockercompose.stop /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
def pause(path, service_names=None):
'''
Pause running containers in the docker-compose file, service_names is a python
list, if omitted pause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.pause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'paused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pausing containers via docker-compose', result, debug_ret)
def unpause(path, service_names=None):
'''
Un-Pause containers in the docker-compose file, service_names is a python
list, if omitted unpause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will un-pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.unpause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'unpaused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Un-Pausing containers via docker-compose', result, debug_ret)
def start(path, service_names=None):
'''
Start containers in the docker-compose file, service_names is a python
list, if omitted start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.start /path/where/docker-compose/stored
salt myminion dockercompose.start /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.start(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'started'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Starting containers via docker-compose', result, debug_ret)
def kill(path, service_names=None):
'''
Kill containers in the docker-compose file, service_names is a python
list, if omitted kill all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will kill only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.kill /path/where/docker-compose/stored
salt myminion dockercompose.kill /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.kill(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'killed'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Killing containers via docker-compose', result, debug_ret)
def rm(path, service_names=None):
'''
Remove stopped containers in the docker-compose file, service_names is a python
list, if omitted remove all stopped containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will remove only the specified stopped services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.rm /path/where/docker-compose/stored
salt myminion dockercompose.rm /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.remove_stopped(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Removing stopped containers via docker-compose', None, None)
def ps(path):
'''
List all running containers and report some information about them
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.ps /path/where/docker-compose/stored
'''
project = __load_project(path)
result = {}
if isinstance(project, dict):
return project
else:
if USE_FILTERCLASS:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, OneOffFilter.only),
key=attrgetter('name'))
else:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, one_off=True),
key=attrgetter('name'))
for container in containers:
command = container.human_readable_command
if len(command) > 30:
command = '{0} ...'.format(command[:26])
result[container.name] = {
'id': container.id,
'name': container.name,
'command': command,
'state': container.human_readable_state,
'ports': container.human_readable_ports,
}
return __standardize_result(True, 'Listing docker-compose containers', result, None)
def up(path, service_names=None):
'''
Create and start containers defined in the docker-compose.yml file
located in path, service_names is a python list, if omitted create and
start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will create and start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.up /path/where/docker-compose/stored
salt myminion dockercompose.up /path/where/docker-compose/stored '[janus]'
'''
debug_ret = {}
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
result = _get_convergence_plans(project, service_names)
ret = project.up(service_names)
if debug:
for container in ret:
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Adding containers via docker-compose', result, debug_ret)
def service_create(path, service_name, definition):
'''
Create the definition of a docker-compose service
This fails when the service already exists
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service {0} created'.format(service_name),
already_existed=True)
def service_upsert(path, service_name, definition):
'''
Create or update the definition of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_upsert /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service definition for {0} is set'.format(service_name),
already_existed=True)
def service_remove(path, service_name):
'''
Remove the definition of a docker-compose service
This does not rm the container
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_remove /path/where/docker-compose/stored service_name
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
del services[service_name]
return __dump_compose_file(path, compose_result,
'Service {0} is removed from {1}'.format(service_name, path),
already_existed=True)
def service_set_tag(path, service_name, tag):
'''
Change the tag of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
tag
Name of the tag (often used as version) that the service image should have
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name tag
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
if 'image' not in services[service_name]:
return __standardize_result(False,
'Service {0} did not contain the variable "image"'.format(service_name),
None, None)
image = services[service_name]['image'].split(':')[0]
services[service_name]['image'] = '{0}:{1}'.format(image, tag)
return __dump_compose_file(path, compose_result,
'Service {0} is set to tag "{1}"'.format(service_name, tag),
already_existed=True)
|
saltstack/salt
|
salt/modules/dockercompose.py
|
__read_docker_compose_file
|
python
|
def __read_docker_compose_file(file_path):
'''
Read the compose file if it exists in the directory
:param file_path:
:return:
'''
if not os.path.isfile(file_path):
return __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
file_name = os.path.basename(file_path)
result = {file_name: ''}
for line in fl:
result[file_name] += salt.utils.stringutils.to_unicode(line)
except EnvironmentError:
return __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
return __standardize_result(True,
'Reading content of {0}'.format(file_path),
result, None)
|
Read the compose file if it exists in the directory
:param file_path:
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockercompose.py#L200-L223
| null |
# -*- coding: utf-8 -*-
'''
Module to import docker-compose via saltstack
.. versionadded:: 2016.3.0
:maintainer: Jean Praloran <jeanpralo@gmail.com>
:maturity: new
:depends: docker-compose>=1.5
:platform: all
Introduction
------------
This module allows one to deal with docker-compose file in a directory.
This is a first version only, the following commands are missing at the moment
but will be built later on if the community is interested in this module:
- run
- logs
- port
- scale
Installation Prerequisites
--------------------------
This execution module requires at least version 1.4.0 of both docker-compose_ and
Docker_. docker-compose can easily be installed using :py:func:`pip.install
<salt.modules.pip.install>`:
.. code-block:: bash
salt myminion pip.install docker-compose>=1.5.0
.. _docker-compose: https://pypi.python.org/pypi/docker-compose
.. _Docker: https://www.docker.com/
How to use this module?
-----------------------
In order to use the module if you have no docker-compose file on the server you
can issue the command create, it takes two arguments the path where the
docker-compose.yml will be stored and the content of this latter:
.. code-block:: text
# salt-call -l debug dockercompose.create /tmp/toto '
database:
image: mongo:3.0
command: mongod --smallfiles --quiet --logpath=/dev/null
'
Then you can execute a list of method defined at the bottom with at least one
argument (the path where the docker-compose.yml will be read) and an optional
python list which corresponds to the services names:
.. code-block:: bash
# salt-call -l debug dockercompose.up /tmp/toto
# salt-call -l debug dockercompose.restart /tmp/toto '[database]'
# salt-call -l debug dockercompose.stop /tmp/toto
# salt-call -l debug dockercompose.rm /tmp/toto
Docker-compose method supported
-------------------------------
- up
- restart
- stop
- start
- pause
- unpause
- kill
- rm
- ps
- pull
- build
Functions
---------
- docker-compose.yml management
- :py:func:`dockercompose.create <salt.modules.dockercompose.create>`
- :py:func:`dockercompose.get <salt.modules.dockercompose.get>`
- Manage containers
- :py:func:`dockercompose.restart <salt.modules.dockercompose.restart>`
- :py:func:`dockercompose.stop <salt.modules.dockercompose.stop>`
- :py:func:`dockercompose.pause <salt.modules.dockercompose.pause>`
- :py:func:`dockercompose.unpause <salt.modules.dockercompose.unpause>`
- :py:func:`dockercompose.start <salt.modules.dockercompose.start>`
- :py:func:`dockercompose.kill <salt.modules.dockercompose.kill>`
- :py:func:`dockercompose.rm <salt.modules.dockercompose.rm>`
- :py:func:`dockercompose.up <salt.modules.dockercompose.up>`
- Manage containers image:
- :py:func:`dockercompose.pull <salt.modules.dockercompose.pull>`
- :py:func:`dockercompose.build <salt.modules.dockercompose.build>`
- Gather information about containers:
- :py:func:`dockercompose.ps <salt.modules.dockercompose.ps>`
- Manage service definitions:
- :py:func:`dockercompose.service_create <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_upsert <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_remove <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_set_tag <salt.modules.dockercompose.ps>`
Detailed Function Documentation
-------------------------------
'''
from __future__ import absolute_import, print_function, unicode_literals
import inspect
import logging
import os
import re
import salt.utils.files
import salt.utils.stringutils
from salt.ext import six
from operator import attrgetter
from salt.serializers import json
from salt.utils import yaml
try:
import compose
from compose.cli.command import get_project
from compose.service import ConvergenceStrategy
HAS_DOCKERCOMPOSE = True
except ImportError:
HAS_DOCKERCOMPOSE = False
try:
from compose.project import OneOffFilter
USE_FILTERCLASS = True
except ImportError:
USE_FILTERCLASS = False
MIN_DOCKERCOMPOSE = (1, 5, 0)
VERSION_RE = r'([\d.]+)'
log = logging.getLogger(__name__)
debug = False
__virtualname__ = 'dockercompose'
DEFAULT_DC_FILENAMES = ('docker-compose.yml', 'docker-compose.yaml')
def __virtual__():
if HAS_DOCKERCOMPOSE:
match = re.match(VERSION_RE, six.text_type(compose.__version__))
if match:
version = tuple([int(x) for x in match.group(1).split('.')])
if version >= MIN_DOCKERCOMPOSE:
return __virtualname__
return (False, 'The dockercompose execution module not loaded: '
'compose python library not available.')
def __standardize_result(status, message, data=None, debug_msg=None):
'''
Standardizes all responses
:param status:
:param message:
:param data:
:param debug_msg:
:return:
'''
result = {
'status': status,
'message': message
}
if data is not None:
result['return'] = data
if debug_msg is not None and debug:
result['debug'] = debug_msg
return result
def __get_docker_file_path(path):
'''
Determines the filepath to use
:param path:
:return:
'''
if os.path.isfile(path):
return path
for dc_filename in DEFAULT_DC_FILENAMES:
file_path = os.path.join(path, dc_filename)
if os.path.isfile(file_path):
return file_path
# implicitly return None
def __load_docker_compose(path):
'''
Read the compose file and load its' contents
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return None, __standardize_result(False, msg,
None, None)
if not os.path.isfile(file_path):
return None, __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
loaded = yaml.load(fl)
except EnvironmentError:
return None, __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(file_path, yerr)
return None, __standardize_result(False, msg,
None, None)
if not loaded:
msg = 'Got empty compose file at {0}'.format(file_path)
return None, __standardize_result(False, msg,
None, None)
if 'services' not in loaded:
loaded['services'] = {}
result = {
'compose_content': loaded,
'file_name': os.path.basename(file_path)
}
return result, None
def __dump_docker_compose(path, content, already_existed):
'''
Dumps
:param path:
:param content: the not-yet dumped content
:return:
'''
try:
dumped = yaml.safe_dump(content, indent=2, default_flow_style=False)
return __write_docker_compose(path, dumped, already_existed)
except TypeError as t_err:
msg = 'Could not dump {0} {1}'.format(content, t_err)
return __standardize_result(False, msg,
None, None)
def __write_docker_compose(path, docker_compose, already_existed):
'''
Write docker-compose to a path
in order to use it with docker-compose ( config check )
:param path:
docker_compose
contains the docker-compose file
:return:
'''
if path.lower().endswith(('.yml', '.yaml')):
file_path = path
dir_name = os.path.dirname(path)
else:
dir_name = path
file_path = os.path.join(dir_name, DEFAULT_DC_FILENAMES[0])
if os.path.isdir(dir_name) is False:
os.mkdir(dir_name)
try:
with salt.utils.files.fopen(file_path, 'w') as fl:
fl.write(salt.utils.stringutils.to_str(docker_compose))
except EnvironmentError:
return __standardize_result(False,
'Could not write {0}'.format(file_path),
None, None)
project = __load_project_from_file_path(file_path)
if isinstance(project, dict):
if not already_existed:
os.remove(file_path)
return project
return file_path
def __load_project(path):
'''
Load a docker-compose project from path
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return __standardize_result(False,
msg,
None, None)
return __load_project_from_file_path(file_path)
def __load_project_from_file_path(file_path):
'''
Load a docker-compose project from file path
:param path:
:return:
'''
try:
project = get_project(project_dir=os.path.dirname(file_path),
config_path=[os.path.basename(file_path)])
except Exception as inst:
return __handle_except(inst)
return project
def __load_compose_definitions(path, definition):
'''
Will load the compose file located at path
Then determines the format/contents of the sent definition
err or results are only set if there were any
:param path:
:param definition:
:return tuple(compose_result, loaded_definition, err):
'''
compose_result, err = __load_docker_compose(path)
if err:
return None, None, err
if isinstance(definition, dict):
return compose_result, definition, None
elif definition.strip().startswith('{'):
try:
loaded_definition = json.deserialize(definition)
except json.DeserializationError as jerr:
msg = 'Could not parse {0} {1}'.format(definition, jerr)
return None, None, __standardize_result(False, msg,
None, None)
else:
try:
loaded_definition = yaml.load(definition)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(definition, yerr)
return None, None, __standardize_result(False, msg,
None, None)
return compose_result, loaded_definition, None
def __dump_compose_file(path, compose_result, success_msg, already_existed):
'''
Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return:
'''
ret = __dump_docker_compose(path,
compose_result['compose_content'],
already_existed)
if isinstance(ret, dict):
return ret
return __standardize_result(True, success_msg,
compose_result['compose_content'], None)
def __handle_except(inst):
'''
Handle exception and return a standard result
:param inst:
:return:
'''
return __standardize_result(False,
'Docker-compose command {0} failed'.
format(inspect.stack()[1][3]),
'{0}'.format(inst), None)
def _get_convergence_plans(project, service_names):
'''
Get action executed for each container
:param project:
:param service_names:
:return:
'''
ret = {}
plans = project._get_convergence_plans(project.get_services(service_names),
ConvergenceStrategy.changed)
for cont in plans:
(action, container) = plans[cont]
if action == 'create':
ret[cont] = 'Creating container'
elif action == 'recreate':
ret[cont] = 'Re-creating container'
elif action == 'start':
ret[cont] = 'Starting container'
elif action == 'noop':
ret[cont] = 'Container is up to date'
return ret
def get(path):
'''
Get the content of the docker-compose file into a directory
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.get /path/where/docker-compose/stored
'''
file_path = __get_docker_file_path(path)
if file_path is None:
return __standardize_result(False,
'Path {} is not present'.format(path),
None, None)
salt_result = __read_docker_compose_file(file_path)
if not salt_result['status']:
return salt_result
project = __load_project(path)
if isinstance(project, dict):
salt_result['return']['valid'] = False
else:
salt_result['return']['valid'] = True
return salt_result
def create(path, docker_compose):
'''
Create and validate a docker-compose file into a directory
path
Path where the docker-compose file will be stored on the server
docker_compose
docker_compose file
CLI Example:
.. code-block:: bash
salt myminion dockercompose.create /path/where/docker-compose/stored content
'''
if docker_compose:
ret = __write_docker_compose(path,
docker_compose,
already_existed=False)
if isinstance(ret, dict):
return ret
else:
return __standardize_result(False,
'Creating a docker-compose project failed, you must send a valid docker-compose file',
None, None)
return __standardize_result(True,
'Successfully created the docker-compose file',
{'compose.base_dir': path},
None)
def pull(path, service_names=None):
'''
Pull image for containers in the docker-compose file, service_names is a
python list, if omitted pull all images
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pull /path/where/docker-compose/stored
salt myminion dockercompose.pull /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.pull(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pulling containers images via docker-compose succeeded',
None, None)
def build(path, service_names=None):
'''
Build image for containers in the docker-compose file, service_names is a
python list, if omitted build images for all containers. Please note
that at the moment the module does not allow you to upload your Dockerfile,
nor any other file you could need with your docker-compose.yml, you will
have to make sure the files you need are actually in the directory specified
in the `build` keyword
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.build /path/where/docker-compose/stored
salt myminion dockercompose.build /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.build(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Building containers images via docker-compose succeeded',
None, None)
def restart(path, service_names=None):
'''
Restart container(s) in the docker-compose file, service_names is a python
list, if omitted restart all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will restart only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.restart /path/where/docker-compose/stored
salt myminion dockercompose.restart /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.restart(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'restarted'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Restarting containers via docker-compose', result, debug_ret)
def stop(path, service_names=None):
'''
Stop running containers in the docker-compose file, service_names is a python
list, if omitted stop all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will stop only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.stop /path/where/docker-compose/stored
salt myminion dockercompose.stop /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
def pause(path, service_names=None):
'''
Pause running containers in the docker-compose file, service_names is a python
list, if omitted pause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.pause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'paused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pausing containers via docker-compose', result, debug_ret)
def unpause(path, service_names=None):
'''
Un-Pause containers in the docker-compose file, service_names is a python
list, if omitted unpause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will un-pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.unpause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'unpaused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Un-Pausing containers via docker-compose', result, debug_ret)
def start(path, service_names=None):
'''
Start containers in the docker-compose file, service_names is a python
list, if omitted start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.start /path/where/docker-compose/stored
salt myminion dockercompose.start /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.start(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'started'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Starting containers via docker-compose', result, debug_ret)
def kill(path, service_names=None):
'''
Kill containers in the docker-compose file, service_names is a python
list, if omitted kill all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will kill only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.kill /path/where/docker-compose/stored
salt myminion dockercompose.kill /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.kill(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'killed'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Killing containers via docker-compose', result, debug_ret)
def rm(path, service_names=None):
'''
Remove stopped containers in the docker-compose file, service_names is a python
list, if omitted remove all stopped containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will remove only the specified stopped services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.rm /path/where/docker-compose/stored
salt myminion dockercompose.rm /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.remove_stopped(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Removing stopped containers via docker-compose', None, None)
def ps(path):
'''
List all running containers and report some information about them
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.ps /path/where/docker-compose/stored
'''
project = __load_project(path)
result = {}
if isinstance(project, dict):
return project
else:
if USE_FILTERCLASS:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, OneOffFilter.only),
key=attrgetter('name'))
else:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, one_off=True),
key=attrgetter('name'))
for container in containers:
command = container.human_readable_command
if len(command) > 30:
command = '{0} ...'.format(command[:26])
result[container.name] = {
'id': container.id,
'name': container.name,
'command': command,
'state': container.human_readable_state,
'ports': container.human_readable_ports,
}
return __standardize_result(True, 'Listing docker-compose containers', result, None)
def up(path, service_names=None):
'''
Create and start containers defined in the docker-compose.yml file
located in path, service_names is a python list, if omitted create and
start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will create and start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.up /path/where/docker-compose/stored
salt myminion dockercompose.up /path/where/docker-compose/stored '[janus]'
'''
debug_ret = {}
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
result = _get_convergence_plans(project, service_names)
ret = project.up(service_names)
if debug:
for container in ret:
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Adding containers via docker-compose', result, debug_ret)
def service_create(path, service_name, definition):
'''
Create the definition of a docker-compose service
This fails when the service already exists
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service {0} created'.format(service_name),
already_existed=True)
def service_upsert(path, service_name, definition):
'''
Create or update the definition of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_upsert /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service definition for {0} is set'.format(service_name),
already_existed=True)
def service_remove(path, service_name):
'''
Remove the definition of a docker-compose service
This does not rm the container
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_remove /path/where/docker-compose/stored service_name
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
del services[service_name]
return __dump_compose_file(path, compose_result,
'Service {0} is removed from {1}'.format(service_name, path),
already_existed=True)
def service_set_tag(path, service_name, tag):
'''
Change the tag of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
tag
Name of the tag (often used as version) that the service image should have
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name tag
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
if 'image' not in services[service_name]:
return __standardize_result(False,
'Service {0} did not contain the variable "image"'.format(service_name),
None, None)
image = services[service_name]['image'].split(':')[0]
services[service_name]['image'] = '{0}:{1}'.format(image, tag)
return __dump_compose_file(path, compose_result,
'Service {0} is set to tag "{1}"'.format(service_name, tag),
already_existed=True)
|
saltstack/salt
|
salt/modules/dockercompose.py
|
__load_docker_compose
|
python
|
def __load_docker_compose(path):
'''
Read the compose file and load its' contents
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return None, __standardize_result(False, msg,
None, None)
if not os.path.isfile(file_path):
return None, __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
loaded = yaml.load(fl)
except EnvironmentError:
return None, __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(file_path, yerr)
return None, __standardize_result(False, msg,
None, None)
if not loaded:
msg = 'Got empty compose file at {0}'.format(file_path)
return None, __standardize_result(False, msg,
None, None)
if 'services' not in loaded:
loaded['services'] = {}
result = {
'compose_content': loaded,
'file_name': os.path.basename(file_path)
}
return result, None
|
Read the compose file and load its' contents
:param path:
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockercompose.py#L226-L263
|
[
"def load(stream, Loader=SaltYamlSafeLoader):\n return yaml.load(stream, Loader=Loader)\n",
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def __standardize_result(status, message, data=None, debug_msg=None):\n '''\n Standardizes all responses\n\n :param status:\n :param message:\n :param data:\n :param debug_msg:\n :return:\n '''\n result = {\n 'status': status,\n 'message': message\n }\n\n if data is not None:\n result['return'] = data\n\n if debug_msg is not None and debug:\n result['debug'] = debug_msg\n\n return result\n",
"def __get_docker_file_path(path):\n '''\n Determines the filepath to use\n\n :param path:\n :return:\n '''\n if os.path.isfile(path):\n return path\n for dc_filename in DEFAULT_DC_FILENAMES:\n file_path = os.path.join(path, dc_filename)\n if os.path.isfile(file_path):\n return file_path\n"
] |
# -*- coding: utf-8 -*-
'''
Module to import docker-compose via saltstack
.. versionadded:: 2016.3.0
:maintainer: Jean Praloran <jeanpralo@gmail.com>
:maturity: new
:depends: docker-compose>=1.5
:platform: all
Introduction
------------
This module allows one to deal with docker-compose file in a directory.
This is a first version only, the following commands are missing at the moment
but will be built later on if the community is interested in this module:
- run
- logs
- port
- scale
Installation Prerequisites
--------------------------
This execution module requires at least version 1.4.0 of both docker-compose_ and
Docker_. docker-compose can easily be installed using :py:func:`pip.install
<salt.modules.pip.install>`:
.. code-block:: bash
salt myminion pip.install docker-compose>=1.5.0
.. _docker-compose: https://pypi.python.org/pypi/docker-compose
.. _Docker: https://www.docker.com/
How to use this module?
-----------------------
In order to use the module if you have no docker-compose file on the server you
can issue the command create, it takes two arguments the path where the
docker-compose.yml will be stored and the content of this latter:
.. code-block:: text
# salt-call -l debug dockercompose.create /tmp/toto '
database:
image: mongo:3.0
command: mongod --smallfiles --quiet --logpath=/dev/null
'
Then you can execute a list of method defined at the bottom with at least one
argument (the path where the docker-compose.yml will be read) and an optional
python list which corresponds to the services names:
.. code-block:: bash
# salt-call -l debug dockercompose.up /tmp/toto
# salt-call -l debug dockercompose.restart /tmp/toto '[database]'
# salt-call -l debug dockercompose.stop /tmp/toto
# salt-call -l debug dockercompose.rm /tmp/toto
Docker-compose method supported
-------------------------------
- up
- restart
- stop
- start
- pause
- unpause
- kill
- rm
- ps
- pull
- build
Functions
---------
- docker-compose.yml management
- :py:func:`dockercompose.create <salt.modules.dockercompose.create>`
- :py:func:`dockercompose.get <salt.modules.dockercompose.get>`
- Manage containers
- :py:func:`dockercompose.restart <salt.modules.dockercompose.restart>`
- :py:func:`dockercompose.stop <salt.modules.dockercompose.stop>`
- :py:func:`dockercompose.pause <salt.modules.dockercompose.pause>`
- :py:func:`dockercompose.unpause <salt.modules.dockercompose.unpause>`
- :py:func:`dockercompose.start <salt.modules.dockercompose.start>`
- :py:func:`dockercompose.kill <salt.modules.dockercompose.kill>`
- :py:func:`dockercompose.rm <salt.modules.dockercompose.rm>`
- :py:func:`dockercompose.up <salt.modules.dockercompose.up>`
- Manage containers image:
- :py:func:`dockercompose.pull <salt.modules.dockercompose.pull>`
- :py:func:`dockercompose.build <salt.modules.dockercompose.build>`
- Gather information about containers:
- :py:func:`dockercompose.ps <salt.modules.dockercompose.ps>`
- Manage service definitions:
- :py:func:`dockercompose.service_create <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_upsert <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_remove <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_set_tag <salt.modules.dockercompose.ps>`
Detailed Function Documentation
-------------------------------
'''
from __future__ import absolute_import, print_function, unicode_literals
import inspect
import logging
import os
import re
import salt.utils.files
import salt.utils.stringutils
from salt.ext import six
from operator import attrgetter
from salt.serializers import json
from salt.utils import yaml
try:
import compose
from compose.cli.command import get_project
from compose.service import ConvergenceStrategy
HAS_DOCKERCOMPOSE = True
except ImportError:
HAS_DOCKERCOMPOSE = False
try:
from compose.project import OneOffFilter
USE_FILTERCLASS = True
except ImportError:
USE_FILTERCLASS = False
MIN_DOCKERCOMPOSE = (1, 5, 0)
VERSION_RE = r'([\d.]+)'
log = logging.getLogger(__name__)
debug = False
__virtualname__ = 'dockercompose'
DEFAULT_DC_FILENAMES = ('docker-compose.yml', 'docker-compose.yaml')
def __virtual__():
if HAS_DOCKERCOMPOSE:
match = re.match(VERSION_RE, six.text_type(compose.__version__))
if match:
version = tuple([int(x) for x in match.group(1).split('.')])
if version >= MIN_DOCKERCOMPOSE:
return __virtualname__
return (False, 'The dockercompose execution module not loaded: '
'compose python library not available.')
def __standardize_result(status, message, data=None, debug_msg=None):
'''
Standardizes all responses
:param status:
:param message:
:param data:
:param debug_msg:
:return:
'''
result = {
'status': status,
'message': message
}
if data is not None:
result['return'] = data
if debug_msg is not None and debug:
result['debug'] = debug_msg
return result
def __get_docker_file_path(path):
'''
Determines the filepath to use
:param path:
:return:
'''
if os.path.isfile(path):
return path
for dc_filename in DEFAULT_DC_FILENAMES:
file_path = os.path.join(path, dc_filename)
if os.path.isfile(file_path):
return file_path
# implicitly return None
def __read_docker_compose_file(file_path):
'''
Read the compose file if it exists in the directory
:param file_path:
:return:
'''
if not os.path.isfile(file_path):
return __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
file_name = os.path.basename(file_path)
result = {file_name: ''}
for line in fl:
result[file_name] += salt.utils.stringutils.to_unicode(line)
except EnvironmentError:
return __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
return __standardize_result(True,
'Reading content of {0}'.format(file_path),
result, None)
def __dump_docker_compose(path, content, already_existed):
'''
Dumps
:param path:
:param content: the not-yet dumped content
:return:
'''
try:
dumped = yaml.safe_dump(content, indent=2, default_flow_style=False)
return __write_docker_compose(path, dumped, already_existed)
except TypeError as t_err:
msg = 'Could not dump {0} {1}'.format(content, t_err)
return __standardize_result(False, msg,
None, None)
def __write_docker_compose(path, docker_compose, already_existed):
'''
Write docker-compose to a path
in order to use it with docker-compose ( config check )
:param path:
docker_compose
contains the docker-compose file
:return:
'''
if path.lower().endswith(('.yml', '.yaml')):
file_path = path
dir_name = os.path.dirname(path)
else:
dir_name = path
file_path = os.path.join(dir_name, DEFAULT_DC_FILENAMES[0])
if os.path.isdir(dir_name) is False:
os.mkdir(dir_name)
try:
with salt.utils.files.fopen(file_path, 'w') as fl:
fl.write(salt.utils.stringutils.to_str(docker_compose))
except EnvironmentError:
return __standardize_result(False,
'Could not write {0}'.format(file_path),
None, None)
project = __load_project_from_file_path(file_path)
if isinstance(project, dict):
if not already_existed:
os.remove(file_path)
return project
return file_path
def __load_project(path):
'''
Load a docker-compose project from path
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return __standardize_result(False,
msg,
None, None)
return __load_project_from_file_path(file_path)
def __load_project_from_file_path(file_path):
'''
Load a docker-compose project from file path
:param path:
:return:
'''
try:
project = get_project(project_dir=os.path.dirname(file_path),
config_path=[os.path.basename(file_path)])
except Exception as inst:
return __handle_except(inst)
return project
def __load_compose_definitions(path, definition):
'''
Will load the compose file located at path
Then determines the format/contents of the sent definition
err or results are only set if there were any
:param path:
:param definition:
:return tuple(compose_result, loaded_definition, err):
'''
compose_result, err = __load_docker_compose(path)
if err:
return None, None, err
if isinstance(definition, dict):
return compose_result, definition, None
elif definition.strip().startswith('{'):
try:
loaded_definition = json.deserialize(definition)
except json.DeserializationError as jerr:
msg = 'Could not parse {0} {1}'.format(definition, jerr)
return None, None, __standardize_result(False, msg,
None, None)
else:
try:
loaded_definition = yaml.load(definition)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(definition, yerr)
return None, None, __standardize_result(False, msg,
None, None)
return compose_result, loaded_definition, None
def __dump_compose_file(path, compose_result, success_msg, already_existed):
'''
Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return:
'''
ret = __dump_docker_compose(path,
compose_result['compose_content'],
already_existed)
if isinstance(ret, dict):
return ret
return __standardize_result(True, success_msg,
compose_result['compose_content'], None)
def __handle_except(inst):
'''
Handle exception and return a standard result
:param inst:
:return:
'''
return __standardize_result(False,
'Docker-compose command {0} failed'.
format(inspect.stack()[1][3]),
'{0}'.format(inst), None)
def _get_convergence_plans(project, service_names):
'''
Get action executed for each container
:param project:
:param service_names:
:return:
'''
ret = {}
plans = project._get_convergence_plans(project.get_services(service_names),
ConvergenceStrategy.changed)
for cont in plans:
(action, container) = plans[cont]
if action == 'create':
ret[cont] = 'Creating container'
elif action == 'recreate':
ret[cont] = 'Re-creating container'
elif action == 'start':
ret[cont] = 'Starting container'
elif action == 'noop':
ret[cont] = 'Container is up to date'
return ret
def get(path):
'''
Get the content of the docker-compose file into a directory
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.get /path/where/docker-compose/stored
'''
file_path = __get_docker_file_path(path)
if file_path is None:
return __standardize_result(False,
'Path {} is not present'.format(path),
None, None)
salt_result = __read_docker_compose_file(file_path)
if not salt_result['status']:
return salt_result
project = __load_project(path)
if isinstance(project, dict):
salt_result['return']['valid'] = False
else:
salt_result['return']['valid'] = True
return salt_result
def create(path, docker_compose):
'''
Create and validate a docker-compose file into a directory
path
Path where the docker-compose file will be stored on the server
docker_compose
docker_compose file
CLI Example:
.. code-block:: bash
salt myminion dockercompose.create /path/where/docker-compose/stored content
'''
if docker_compose:
ret = __write_docker_compose(path,
docker_compose,
already_existed=False)
if isinstance(ret, dict):
return ret
else:
return __standardize_result(False,
'Creating a docker-compose project failed, you must send a valid docker-compose file',
None, None)
return __standardize_result(True,
'Successfully created the docker-compose file',
{'compose.base_dir': path},
None)
def pull(path, service_names=None):
'''
Pull image for containers in the docker-compose file, service_names is a
python list, if omitted pull all images
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pull /path/where/docker-compose/stored
salt myminion dockercompose.pull /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.pull(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pulling containers images via docker-compose succeeded',
None, None)
def build(path, service_names=None):
'''
Build image for containers in the docker-compose file, service_names is a
python list, if omitted build images for all containers. Please note
that at the moment the module does not allow you to upload your Dockerfile,
nor any other file you could need with your docker-compose.yml, you will
have to make sure the files you need are actually in the directory specified
in the `build` keyword
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.build /path/where/docker-compose/stored
salt myminion dockercompose.build /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.build(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Building containers images via docker-compose succeeded',
None, None)
def restart(path, service_names=None):
'''
Restart container(s) in the docker-compose file, service_names is a python
list, if omitted restart all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will restart only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.restart /path/where/docker-compose/stored
salt myminion dockercompose.restart /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.restart(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'restarted'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Restarting containers via docker-compose', result, debug_ret)
def stop(path, service_names=None):
'''
Stop running containers in the docker-compose file, service_names is a python
list, if omitted stop all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will stop only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.stop /path/where/docker-compose/stored
salt myminion dockercompose.stop /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
def pause(path, service_names=None):
'''
Pause running containers in the docker-compose file, service_names is a python
list, if omitted pause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.pause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'paused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pausing containers via docker-compose', result, debug_ret)
def unpause(path, service_names=None):
'''
Un-Pause containers in the docker-compose file, service_names is a python
list, if omitted unpause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will un-pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.unpause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'unpaused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Un-Pausing containers via docker-compose', result, debug_ret)
def start(path, service_names=None):
'''
Start containers in the docker-compose file, service_names is a python
list, if omitted start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.start /path/where/docker-compose/stored
salt myminion dockercompose.start /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.start(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'started'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Starting containers via docker-compose', result, debug_ret)
def kill(path, service_names=None):
'''
Kill containers in the docker-compose file, service_names is a python
list, if omitted kill all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will kill only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.kill /path/where/docker-compose/stored
salt myminion dockercompose.kill /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.kill(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'killed'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Killing containers via docker-compose', result, debug_ret)
def rm(path, service_names=None):
'''
Remove stopped containers in the docker-compose file, service_names is a python
list, if omitted remove all stopped containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will remove only the specified stopped services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.rm /path/where/docker-compose/stored
salt myminion dockercompose.rm /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.remove_stopped(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Removing stopped containers via docker-compose', None, None)
def ps(path):
'''
List all running containers and report some information about them
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.ps /path/where/docker-compose/stored
'''
project = __load_project(path)
result = {}
if isinstance(project, dict):
return project
else:
if USE_FILTERCLASS:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, OneOffFilter.only),
key=attrgetter('name'))
else:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, one_off=True),
key=attrgetter('name'))
for container in containers:
command = container.human_readable_command
if len(command) > 30:
command = '{0} ...'.format(command[:26])
result[container.name] = {
'id': container.id,
'name': container.name,
'command': command,
'state': container.human_readable_state,
'ports': container.human_readable_ports,
}
return __standardize_result(True, 'Listing docker-compose containers', result, None)
def up(path, service_names=None):
'''
Create and start containers defined in the docker-compose.yml file
located in path, service_names is a python list, if omitted create and
start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will create and start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.up /path/where/docker-compose/stored
salt myminion dockercompose.up /path/where/docker-compose/stored '[janus]'
'''
debug_ret = {}
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
result = _get_convergence_plans(project, service_names)
ret = project.up(service_names)
if debug:
for container in ret:
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Adding containers via docker-compose', result, debug_ret)
def service_create(path, service_name, definition):
'''
Create the definition of a docker-compose service
This fails when the service already exists
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service {0} created'.format(service_name),
already_existed=True)
def service_upsert(path, service_name, definition):
'''
Create or update the definition of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_upsert /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service definition for {0} is set'.format(service_name),
already_existed=True)
def service_remove(path, service_name):
'''
Remove the definition of a docker-compose service
This does not rm the container
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_remove /path/where/docker-compose/stored service_name
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
del services[service_name]
return __dump_compose_file(path, compose_result,
'Service {0} is removed from {1}'.format(service_name, path),
already_existed=True)
def service_set_tag(path, service_name, tag):
'''
Change the tag of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
tag
Name of the tag (often used as version) that the service image should have
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name tag
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
if 'image' not in services[service_name]:
return __standardize_result(False,
'Service {0} did not contain the variable "image"'.format(service_name),
None, None)
image = services[service_name]['image'].split(':')[0]
services[service_name]['image'] = '{0}:{1}'.format(image, tag)
return __dump_compose_file(path, compose_result,
'Service {0} is set to tag "{1}"'.format(service_name, tag),
already_existed=True)
|
saltstack/salt
|
salt/modules/dockercompose.py
|
__dump_docker_compose
|
python
|
def __dump_docker_compose(path, content, already_existed):
'''
Dumps
:param path:
:param content: the not-yet dumped content
:return:
'''
try:
dumped = yaml.safe_dump(content, indent=2, default_flow_style=False)
return __write_docker_compose(path, dumped, already_existed)
except TypeError as t_err:
msg = 'Could not dump {0} {1}'.format(content, t_err)
return __standardize_result(False, msg,
None, None)
|
Dumps
:param path:
:param content: the not-yet dumped content
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockercompose.py#L266-L280
| null |
# -*- coding: utf-8 -*-
'''
Module to import docker-compose via saltstack
.. versionadded:: 2016.3.0
:maintainer: Jean Praloran <jeanpralo@gmail.com>
:maturity: new
:depends: docker-compose>=1.5
:platform: all
Introduction
------------
This module allows one to deal with docker-compose file in a directory.
This is a first version only, the following commands are missing at the moment
but will be built later on if the community is interested in this module:
- run
- logs
- port
- scale
Installation Prerequisites
--------------------------
This execution module requires at least version 1.4.0 of both docker-compose_ and
Docker_. docker-compose can easily be installed using :py:func:`pip.install
<salt.modules.pip.install>`:
.. code-block:: bash
salt myminion pip.install docker-compose>=1.5.0
.. _docker-compose: https://pypi.python.org/pypi/docker-compose
.. _Docker: https://www.docker.com/
How to use this module?
-----------------------
In order to use the module if you have no docker-compose file on the server you
can issue the command create, it takes two arguments the path where the
docker-compose.yml will be stored and the content of this latter:
.. code-block:: text
# salt-call -l debug dockercompose.create /tmp/toto '
database:
image: mongo:3.0
command: mongod --smallfiles --quiet --logpath=/dev/null
'
Then you can execute a list of method defined at the bottom with at least one
argument (the path where the docker-compose.yml will be read) and an optional
python list which corresponds to the services names:
.. code-block:: bash
# salt-call -l debug dockercompose.up /tmp/toto
# salt-call -l debug dockercompose.restart /tmp/toto '[database]'
# salt-call -l debug dockercompose.stop /tmp/toto
# salt-call -l debug dockercompose.rm /tmp/toto
Docker-compose method supported
-------------------------------
- up
- restart
- stop
- start
- pause
- unpause
- kill
- rm
- ps
- pull
- build
Functions
---------
- docker-compose.yml management
- :py:func:`dockercompose.create <salt.modules.dockercompose.create>`
- :py:func:`dockercompose.get <salt.modules.dockercompose.get>`
- Manage containers
- :py:func:`dockercompose.restart <salt.modules.dockercompose.restart>`
- :py:func:`dockercompose.stop <salt.modules.dockercompose.stop>`
- :py:func:`dockercompose.pause <salt.modules.dockercompose.pause>`
- :py:func:`dockercompose.unpause <salt.modules.dockercompose.unpause>`
- :py:func:`dockercompose.start <salt.modules.dockercompose.start>`
- :py:func:`dockercompose.kill <salt.modules.dockercompose.kill>`
- :py:func:`dockercompose.rm <salt.modules.dockercompose.rm>`
- :py:func:`dockercompose.up <salt.modules.dockercompose.up>`
- Manage containers image:
- :py:func:`dockercompose.pull <salt.modules.dockercompose.pull>`
- :py:func:`dockercompose.build <salt.modules.dockercompose.build>`
- Gather information about containers:
- :py:func:`dockercompose.ps <salt.modules.dockercompose.ps>`
- Manage service definitions:
- :py:func:`dockercompose.service_create <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_upsert <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_remove <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_set_tag <salt.modules.dockercompose.ps>`
Detailed Function Documentation
-------------------------------
'''
from __future__ import absolute_import, print_function, unicode_literals
import inspect
import logging
import os
import re
import salt.utils.files
import salt.utils.stringutils
from salt.ext import six
from operator import attrgetter
from salt.serializers import json
from salt.utils import yaml
try:
import compose
from compose.cli.command import get_project
from compose.service import ConvergenceStrategy
HAS_DOCKERCOMPOSE = True
except ImportError:
HAS_DOCKERCOMPOSE = False
try:
from compose.project import OneOffFilter
USE_FILTERCLASS = True
except ImportError:
USE_FILTERCLASS = False
MIN_DOCKERCOMPOSE = (1, 5, 0)
VERSION_RE = r'([\d.]+)'
log = logging.getLogger(__name__)
debug = False
__virtualname__ = 'dockercompose'
DEFAULT_DC_FILENAMES = ('docker-compose.yml', 'docker-compose.yaml')
def __virtual__():
if HAS_DOCKERCOMPOSE:
match = re.match(VERSION_RE, six.text_type(compose.__version__))
if match:
version = tuple([int(x) for x in match.group(1).split('.')])
if version >= MIN_DOCKERCOMPOSE:
return __virtualname__
return (False, 'The dockercompose execution module not loaded: '
'compose python library not available.')
def __standardize_result(status, message, data=None, debug_msg=None):
'''
Standardizes all responses
:param status:
:param message:
:param data:
:param debug_msg:
:return:
'''
result = {
'status': status,
'message': message
}
if data is not None:
result['return'] = data
if debug_msg is not None and debug:
result['debug'] = debug_msg
return result
def __get_docker_file_path(path):
'''
Determines the filepath to use
:param path:
:return:
'''
if os.path.isfile(path):
return path
for dc_filename in DEFAULT_DC_FILENAMES:
file_path = os.path.join(path, dc_filename)
if os.path.isfile(file_path):
return file_path
# implicitly return None
def __read_docker_compose_file(file_path):
'''
Read the compose file if it exists in the directory
:param file_path:
:return:
'''
if not os.path.isfile(file_path):
return __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
file_name = os.path.basename(file_path)
result = {file_name: ''}
for line in fl:
result[file_name] += salt.utils.stringutils.to_unicode(line)
except EnvironmentError:
return __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
return __standardize_result(True,
'Reading content of {0}'.format(file_path),
result, None)
def __load_docker_compose(path):
'''
Read the compose file and load its' contents
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return None, __standardize_result(False, msg,
None, None)
if not os.path.isfile(file_path):
return None, __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
loaded = yaml.load(fl)
except EnvironmentError:
return None, __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(file_path, yerr)
return None, __standardize_result(False, msg,
None, None)
if not loaded:
msg = 'Got empty compose file at {0}'.format(file_path)
return None, __standardize_result(False, msg,
None, None)
if 'services' not in loaded:
loaded['services'] = {}
result = {
'compose_content': loaded,
'file_name': os.path.basename(file_path)
}
return result, None
def __write_docker_compose(path, docker_compose, already_existed):
'''
Write docker-compose to a path
in order to use it with docker-compose ( config check )
:param path:
docker_compose
contains the docker-compose file
:return:
'''
if path.lower().endswith(('.yml', '.yaml')):
file_path = path
dir_name = os.path.dirname(path)
else:
dir_name = path
file_path = os.path.join(dir_name, DEFAULT_DC_FILENAMES[0])
if os.path.isdir(dir_name) is False:
os.mkdir(dir_name)
try:
with salt.utils.files.fopen(file_path, 'w') as fl:
fl.write(salt.utils.stringutils.to_str(docker_compose))
except EnvironmentError:
return __standardize_result(False,
'Could not write {0}'.format(file_path),
None, None)
project = __load_project_from_file_path(file_path)
if isinstance(project, dict):
if not already_existed:
os.remove(file_path)
return project
return file_path
def __load_project(path):
'''
Load a docker-compose project from path
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return __standardize_result(False,
msg,
None, None)
return __load_project_from_file_path(file_path)
def __load_project_from_file_path(file_path):
'''
Load a docker-compose project from file path
:param path:
:return:
'''
try:
project = get_project(project_dir=os.path.dirname(file_path),
config_path=[os.path.basename(file_path)])
except Exception as inst:
return __handle_except(inst)
return project
def __load_compose_definitions(path, definition):
'''
Will load the compose file located at path
Then determines the format/contents of the sent definition
err or results are only set if there were any
:param path:
:param definition:
:return tuple(compose_result, loaded_definition, err):
'''
compose_result, err = __load_docker_compose(path)
if err:
return None, None, err
if isinstance(definition, dict):
return compose_result, definition, None
elif definition.strip().startswith('{'):
try:
loaded_definition = json.deserialize(definition)
except json.DeserializationError as jerr:
msg = 'Could not parse {0} {1}'.format(definition, jerr)
return None, None, __standardize_result(False, msg,
None, None)
else:
try:
loaded_definition = yaml.load(definition)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(definition, yerr)
return None, None, __standardize_result(False, msg,
None, None)
return compose_result, loaded_definition, None
def __dump_compose_file(path, compose_result, success_msg, already_existed):
'''
Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return:
'''
ret = __dump_docker_compose(path,
compose_result['compose_content'],
already_existed)
if isinstance(ret, dict):
return ret
return __standardize_result(True, success_msg,
compose_result['compose_content'], None)
def __handle_except(inst):
'''
Handle exception and return a standard result
:param inst:
:return:
'''
return __standardize_result(False,
'Docker-compose command {0} failed'.
format(inspect.stack()[1][3]),
'{0}'.format(inst), None)
def _get_convergence_plans(project, service_names):
'''
Get action executed for each container
:param project:
:param service_names:
:return:
'''
ret = {}
plans = project._get_convergence_plans(project.get_services(service_names),
ConvergenceStrategy.changed)
for cont in plans:
(action, container) = plans[cont]
if action == 'create':
ret[cont] = 'Creating container'
elif action == 'recreate':
ret[cont] = 'Re-creating container'
elif action == 'start':
ret[cont] = 'Starting container'
elif action == 'noop':
ret[cont] = 'Container is up to date'
return ret
def get(path):
'''
Get the content of the docker-compose file into a directory
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.get /path/where/docker-compose/stored
'''
file_path = __get_docker_file_path(path)
if file_path is None:
return __standardize_result(False,
'Path {} is not present'.format(path),
None, None)
salt_result = __read_docker_compose_file(file_path)
if not salt_result['status']:
return salt_result
project = __load_project(path)
if isinstance(project, dict):
salt_result['return']['valid'] = False
else:
salt_result['return']['valid'] = True
return salt_result
def create(path, docker_compose):
'''
Create and validate a docker-compose file into a directory
path
Path where the docker-compose file will be stored on the server
docker_compose
docker_compose file
CLI Example:
.. code-block:: bash
salt myminion dockercompose.create /path/where/docker-compose/stored content
'''
if docker_compose:
ret = __write_docker_compose(path,
docker_compose,
already_existed=False)
if isinstance(ret, dict):
return ret
else:
return __standardize_result(False,
'Creating a docker-compose project failed, you must send a valid docker-compose file',
None, None)
return __standardize_result(True,
'Successfully created the docker-compose file',
{'compose.base_dir': path},
None)
def pull(path, service_names=None):
'''
Pull image for containers in the docker-compose file, service_names is a
python list, if omitted pull all images
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pull /path/where/docker-compose/stored
salt myminion dockercompose.pull /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.pull(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pulling containers images via docker-compose succeeded',
None, None)
def build(path, service_names=None):
'''
Build image for containers in the docker-compose file, service_names is a
python list, if omitted build images for all containers. Please note
that at the moment the module does not allow you to upload your Dockerfile,
nor any other file you could need with your docker-compose.yml, you will
have to make sure the files you need are actually in the directory specified
in the `build` keyword
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.build /path/where/docker-compose/stored
salt myminion dockercompose.build /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.build(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Building containers images via docker-compose succeeded',
None, None)
def restart(path, service_names=None):
'''
Restart container(s) in the docker-compose file, service_names is a python
list, if omitted restart all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will restart only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.restart /path/where/docker-compose/stored
salt myminion dockercompose.restart /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.restart(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'restarted'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Restarting containers via docker-compose', result, debug_ret)
def stop(path, service_names=None):
'''
Stop running containers in the docker-compose file, service_names is a python
list, if omitted stop all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will stop only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.stop /path/where/docker-compose/stored
salt myminion dockercompose.stop /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
def pause(path, service_names=None):
'''
Pause running containers in the docker-compose file, service_names is a python
list, if omitted pause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.pause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'paused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pausing containers via docker-compose', result, debug_ret)
def unpause(path, service_names=None):
'''
Un-Pause containers in the docker-compose file, service_names is a python
list, if omitted unpause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will un-pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.unpause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'unpaused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Un-Pausing containers via docker-compose', result, debug_ret)
def start(path, service_names=None):
'''
Start containers in the docker-compose file, service_names is a python
list, if omitted start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.start /path/where/docker-compose/stored
salt myminion dockercompose.start /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.start(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'started'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Starting containers via docker-compose', result, debug_ret)
def kill(path, service_names=None):
'''
Kill containers in the docker-compose file, service_names is a python
list, if omitted kill all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will kill only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.kill /path/where/docker-compose/stored
salt myminion dockercompose.kill /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.kill(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'killed'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Killing containers via docker-compose', result, debug_ret)
def rm(path, service_names=None):
'''
Remove stopped containers in the docker-compose file, service_names is a python
list, if omitted remove all stopped containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will remove only the specified stopped services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.rm /path/where/docker-compose/stored
salt myminion dockercompose.rm /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.remove_stopped(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Removing stopped containers via docker-compose', None, None)
def ps(path):
'''
List all running containers and report some information about them
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.ps /path/where/docker-compose/stored
'''
project = __load_project(path)
result = {}
if isinstance(project, dict):
return project
else:
if USE_FILTERCLASS:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, OneOffFilter.only),
key=attrgetter('name'))
else:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, one_off=True),
key=attrgetter('name'))
for container in containers:
command = container.human_readable_command
if len(command) > 30:
command = '{0} ...'.format(command[:26])
result[container.name] = {
'id': container.id,
'name': container.name,
'command': command,
'state': container.human_readable_state,
'ports': container.human_readable_ports,
}
return __standardize_result(True, 'Listing docker-compose containers', result, None)
def up(path, service_names=None):
'''
Create and start containers defined in the docker-compose.yml file
located in path, service_names is a python list, if omitted create and
start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will create and start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.up /path/where/docker-compose/stored
salt myminion dockercompose.up /path/where/docker-compose/stored '[janus]'
'''
debug_ret = {}
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
result = _get_convergence_plans(project, service_names)
ret = project.up(service_names)
if debug:
for container in ret:
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Adding containers via docker-compose', result, debug_ret)
def service_create(path, service_name, definition):
'''
Create the definition of a docker-compose service
This fails when the service already exists
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service {0} created'.format(service_name),
already_existed=True)
def service_upsert(path, service_name, definition):
'''
Create or update the definition of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_upsert /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service definition for {0} is set'.format(service_name),
already_existed=True)
def service_remove(path, service_name):
'''
Remove the definition of a docker-compose service
This does not rm the container
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_remove /path/where/docker-compose/stored service_name
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
del services[service_name]
return __dump_compose_file(path, compose_result,
'Service {0} is removed from {1}'.format(service_name, path),
already_existed=True)
def service_set_tag(path, service_name, tag):
'''
Change the tag of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
tag
Name of the tag (often used as version) that the service image should have
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name tag
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
if 'image' not in services[service_name]:
return __standardize_result(False,
'Service {0} did not contain the variable "image"'.format(service_name),
None, None)
image = services[service_name]['image'].split(':')[0]
services[service_name]['image'] = '{0}:{1}'.format(image, tag)
return __dump_compose_file(path, compose_result,
'Service {0} is set to tag "{1}"'.format(service_name, tag),
already_existed=True)
|
saltstack/salt
|
salt/modules/dockercompose.py
|
__write_docker_compose
|
python
|
def __write_docker_compose(path, docker_compose, already_existed):
'''
Write docker-compose to a path
in order to use it with docker-compose ( config check )
:param path:
docker_compose
contains the docker-compose file
:return:
'''
if path.lower().endswith(('.yml', '.yaml')):
file_path = path
dir_name = os.path.dirname(path)
else:
dir_name = path
file_path = os.path.join(dir_name, DEFAULT_DC_FILENAMES[0])
if os.path.isdir(dir_name) is False:
os.mkdir(dir_name)
try:
with salt.utils.files.fopen(file_path, 'w') as fl:
fl.write(salt.utils.stringutils.to_str(docker_compose))
except EnvironmentError:
return __standardize_result(False,
'Could not write {0}'.format(file_path),
None, None)
project = __load_project_from_file_path(file_path)
if isinstance(project, dict):
if not already_existed:
os.remove(file_path)
return project
return file_path
|
Write docker-compose to a path
in order to use it with docker-compose ( config check )
:param path:
docker_compose
contains the docker-compose file
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockercompose.py#L283-L315
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n",
"def __standardize_result(status, message, data=None, debug_msg=None):\n '''\n Standardizes all responses\n\n :param status:\n :param message:\n :param data:\n :param debug_msg:\n :return:\n '''\n result = {\n 'status': status,\n 'message': message\n }\n\n if data is not None:\n result['return'] = data\n\n if debug_msg is not None and debug:\n result['debug'] = debug_msg\n\n return result\n",
"def __load_project_from_file_path(file_path):\n '''\n Load a docker-compose project from file path\n\n :param path:\n :return:\n '''\n try:\n project = get_project(project_dir=os.path.dirname(file_path),\n config_path=[os.path.basename(file_path)])\n except Exception as inst:\n return __handle_except(inst)\n return project\n"
] |
# -*- coding: utf-8 -*-
'''
Module to import docker-compose via saltstack
.. versionadded:: 2016.3.0
:maintainer: Jean Praloran <jeanpralo@gmail.com>
:maturity: new
:depends: docker-compose>=1.5
:platform: all
Introduction
------------
This module allows one to deal with docker-compose file in a directory.
This is a first version only, the following commands are missing at the moment
but will be built later on if the community is interested in this module:
- run
- logs
- port
- scale
Installation Prerequisites
--------------------------
This execution module requires at least version 1.4.0 of both docker-compose_ and
Docker_. docker-compose can easily be installed using :py:func:`pip.install
<salt.modules.pip.install>`:
.. code-block:: bash
salt myminion pip.install docker-compose>=1.5.0
.. _docker-compose: https://pypi.python.org/pypi/docker-compose
.. _Docker: https://www.docker.com/
How to use this module?
-----------------------
In order to use the module if you have no docker-compose file on the server you
can issue the command create, it takes two arguments the path where the
docker-compose.yml will be stored and the content of this latter:
.. code-block:: text
# salt-call -l debug dockercompose.create /tmp/toto '
database:
image: mongo:3.0
command: mongod --smallfiles --quiet --logpath=/dev/null
'
Then you can execute a list of method defined at the bottom with at least one
argument (the path where the docker-compose.yml will be read) and an optional
python list which corresponds to the services names:
.. code-block:: bash
# salt-call -l debug dockercompose.up /tmp/toto
# salt-call -l debug dockercompose.restart /tmp/toto '[database]'
# salt-call -l debug dockercompose.stop /tmp/toto
# salt-call -l debug dockercompose.rm /tmp/toto
Docker-compose method supported
-------------------------------
- up
- restart
- stop
- start
- pause
- unpause
- kill
- rm
- ps
- pull
- build
Functions
---------
- docker-compose.yml management
- :py:func:`dockercompose.create <salt.modules.dockercompose.create>`
- :py:func:`dockercompose.get <salt.modules.dockercompose.get>`
- Manage containers
- :py:func:`dockercompose.restart <salt.modules.dockercompose.restart>`
- :py:func:`dockercompose.stop <salt.modules.dockercompose.stop>`
- :py:func:`dockercompose.pause <salt.modules.dockercompose.pause>`
- :py:func:`dockercompose.unpause <salt.modules.dockercompose.unpause>`
- :py:func:`dockercompose.start <salt.modules.dockercompose.start>`
- :py:func:`dockercompose.kill <salt.modules.dockercompose.kill>`
- :py:func:`dockercompose.rm <salt.modules.dockercompose.rm>`
- :py:func:`dockercompose.up <salt.modules.dockercompose.up>`
- Manage containers image:
- :py:func:`dockercompose.pull <salt.modules.dockercompose.pull>`
- :py:func:`dockercompose.build <salt.modules.dockercompose.build>`
- Gather information about containers:
- :py:func:`dockercompose.ps <salt.modules.dockercompose.ps>`
- Manage service definitions:
- :py:func:`dockercompose.service_create <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_upsert <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_remove <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_set_tag <salt.modules.dockercompose.ps>`
Detailed Function Documentation
-------------------------------
'''
from __future__ import absolute_import, print_function, unicode_literals
import inspect
import logging
import os
import re
import salt.utils.files
import salt.utils.stringutils
from salt.ext import six
from operator import attrgetter
from salt.serializers import json
from salt.utils import yaml
try:
import compose
from compose.cli.command import get_project
from compose.service import ConvergenceStrategy
HAS_DOCKERCOMPOSE = True
except ImportError:
HAS_DOCKERCOMPOSE = False
try:
from compose.project import OneOffFilter
USE_FILTERCLASS = True
except ImportError:
USE_FILTERCLASS = False
MIN_DOCKERCOMPOSE = (1, 5, 0)
VERSION_RE = r'([\d.]+)'
log = logging.getLogger(__name__)
debug = False
__virtualname__ = 'dockercompose'
DEFAULT_DC_FILENAMES = ('docker-compose.yml', 'docker-compose.yaml')
def __virtual__():
if HAS_DOCKERCOMPOSE:
match = re.match(VERSION_RE, six.text_type(compose.__version__))
if match:
version = tuple([int(x) for x in match.group(1).split('.')])
if version >= MIN_DOCKERCOMPOSE:
return __virtualname__
return (False, 'The dockercompose execution module not loaded: '
'compose python library not available.')
def __standardize_result(status, message, data=None, debug_msg=None):
'''
Standardizes all responses
:param status:
:param message:
:param data:
:param debug_msg:
:return:
'''
result = {
'status': status,
'message': message
}
if data is not None:
result['return'] = data
if debug_msg is not None and debug:
result['debug'] = debug_msg
return result
def __get_docker_file_path(path):
'''
Determines the filepath to use
:param path:
:return:
'''
if os.path.isfile(path):
return path
for dc_filename in DEFAULT_DC_FILENAMES:
file_path = os.path.join(path, dc_filename)
if os.path.isfile(file_path):
return file_path
# implicitly return None
def __read_docker_compose_file(file_path):
'''
Read the compose file if it exists in the directory
:param file_path:
:return:
'''
if not os.path.isfile(file_path):
return __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
file_name = os.path.basename(file_path)
result = {file_name: ''}
for line in fl:
result[file_name] += salt.utils.stringutils.to_unicode(line)
except EnvironmentError:
return __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
return __standardize_result(True,
'Reading content of {0}'.format(file_path),
result, None)
def __load_docker_compose(path):
'''
Read the compose file and load its' contents
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return None, __standardize_result(False, msg,
None, None)
if not os.path.isfile(file_path):
return None, __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
loaded = yaml.load(fl)
except EnvironmentError:
return None, __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(file_path, yerr)
return None, __standardize_result(False, msg,
None, None)
if not loaded:
msg = 'Got empty compose file at {0}'.format(file_path)
return None, __standardize_result(False, msg,
None, None)
if 'services' not in loaded:
loaded['services'] = {}
result = {
'compose_content': loaded,
'file_name': os.path.basename(file_path)
}
return result, None
def __dump_docker_compose(path, content, already_existed):
'''
Dumps
:param path:
:param content: the not-yet dumped content
:return:
'''
try:
dumped = yaml.safe_dump(content, indent=2, default_flow_style=False)
return __write_docker_compose(path, dumped, already_existed)
except TypeError as t_err:
msg = 'Could not dump {0} {1}'.format(content, t_err)
return __standardize_result(False, msg,
None, None)
def __load_project(path):
'''
Load a docker-compose project from path
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return __standardize_result(False,
msg,
None, None)
return __load_project_from_file_path(file_path)
def __load_project_from_file_path(file_path):
'''
Load a docker-compose project from file path
:param path:
:return:
'''
try:
project = get_project(project_dir=os.path.dirname(file_path),
config_path=[os.path.basename(file_path)])
except Exception as inst:
return __handle_except(inst)
return project
def __load_compose_definitions(path, definition):
'''
Will load the compose file located at path
Then determines the format/contents of the sent definition
err or results are only set if there were any
:param path:
:param definition:
:return tuple(compose_result, loaded_definition, err):
'''
compose_result, err = __load_docker_compose(path)
if err:
return None, None, err
if isinstance(definition, dict):
return compose_result, definition, None
elif definition.strip().startswith('{'):
try:
loaded_definition = json.deserialize(definition)
except json.DeserializationError as jerr:
msg = 'Could not parse {0} {1}'.format(definition, jerr)
return None, None, __standardize_result(False, msg,
None, None)
else:
try:
loaded_definition = yaml.load(definition)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(definition, yerr)
return None, None, __standardize_result(False, msg,
None, None)
return compose_result, loaded_definition, None
def __dump_compose_file(path, compose_result, success_msg, already_existed):
'''
Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return:
'''
ret = __dump_docker_compose(path,
compose_result['compose_content'],
already_existed)
if isinstance(ret, dict):
return ret
return __standardize_result(True, success_msg,
compose_result['compose_content'], None)
def __handle_except(inst):
'''
Handle exception and return a standard result
:param inst:
:return:
'''
return __standardize_result(False,
'Docker-compose command {0} failed'.
format(inspect.stack()[1][3]),
'{0}'.format(inst), None)
def _get_convergence_plans(project, service_names):
'''
Get action executed for each container
:param project:
:param service_names:
:return:
'''
ret = {}
plans = project._get_convergence_plans(project.get_services(service_names),
ConvergenceStrategy.changed)
for cont in plans:
(action, container) = plans[cont]
if action == 'create':
ret[cont] = 'Creating container'
elif action == 'recreate':
ret[cont] = 'Re-creating container'
elif action == 'start':
ret[cont] = 'Starting container'
elif action == 'noop':
ret[cont] = 'Container is up to date'
return ret
def get(path):
'''
Get the content of the docker-compose file into a directory
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.get /path/where/docker-compose/stored
'''
file_path = __get_docker_file_path(path)
if file_path is None:
return __standardize_result(False,
'Path {} is not present'.format(path),
None, None)
salt_result = __read_docker_compose_file(file_path)
if not salt_result['status']:
return salt_result
project = __load_project(path)
if isinstance(project, dict):
salt_result['return']['valid'] = False
else:
salt_result['return']['valid'] = True
return salt_result
def create(path, docker_compose):
'''
Create and validate a docker-compose file into a directory
path
Path where the docker-compose file will be stored on the server
docker_compose
docker_compose file
CLI Example:
.. code-block:: bash
salt myminion dockercompose.create /path/where/docker-compose/stored content
'''
if docker_compose:
ret = __write_docker_compose(path,
docker_compose,
already_existed=False)
if isinstance(ret, dict):
return ret
else:
return __standardize_result(False,
'Creating a docker-compose project failed, you must send a valid docker-compose file',
None, None)
return __standardize_result(True,
'Successfully created the docker-compose file',
{'compose.base_dir': path},
None)
def pull(path, service_names=None):
'''
Pull image for containers in the docker-compose file, service_names is a
python list, if omitted pull all images
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pull /path/where/docker-compose/stored
salt myminion dockercompose.pull /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.pull(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pulling containers images via docker-compose succeeded',
None, None)
def build(path, service_names=None):
'''
Build image for containers in the docker-compose file, service_names is a
python list, if omitted build images for all containers. Please note
that at the moment the module does not allow you to upload your Dockerfile,
nor any other file you could need with your docker-compose.yml, you will
have to make sure the files you need are actually in the directory specified
in the `build` keyword
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.build /path/where/docker-compose/stored
salt myminion dockercompose.build /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.build(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Building containers images via docker-compose succeeded',
None, None)
def restart(path, service_names=None):
'''
Restart container(s) in the docker-compose file, service_names is a python
list, if omitted restart all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will restart only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.restart /path/where/docker-compose/stored
salt myminion dockercompose.restart /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.restart(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'restarted'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Restarting containers via docker-compose', result, debug_ret)
def stop(path, service_names=None):
'''
Stop running containers in the docker-compose file, service_names is a python
list, if omitted stop all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will stop only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.stop /path/where/docker-compose/stored
salt myminion dockercompose.stop /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
def pause(path, service_names=None):
'''
Pause running containers in the docker-compose file, service_names is a python
list, if omitted pause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.pause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'paused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pausing containers via docker-compose', result, debug_ret)
def unpause(path, service_names=None):
'''
Un-Pause containers in the docker-compose file, service_names is a python
list, if omitted unpause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will un-pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.unpause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'unpaused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Un-Pausing containers via docker-compose', result, debug_ret)
def start(path, service_names=None):
'''
Start containers in the docker-compose file, service_names is a python
list, if omitted start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.start /path/where/docker-compose/stored
salt myminion dockercompose.start /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.start(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'started'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Starting containers via docker-compose', result, debug_ret)
def kill(path, service_names=None):
'''
Kill containers in the docker-compose file, service_names is a python
list, if omitted kill all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will kill only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.kill /path/where/docker-compose/stored
salt myminion dockercompose.kill /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.kill(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'killed'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Killing containers via docker-compose', result, debug_ret)
def rm(path, service_names=None):
'''
Remove stopped containers in the docker-compose file, service_names is a python
list, if omitted remove all stopped containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will remove only the specified stopped services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.rm /path/where/docker-compose/stored
salt myminion dockercompose.rm /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.remove_stopped(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Removing stopped containers via docker-compose', None, None)
def ps(path):
'''
List all running containers and report some information about them
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.ps /path/where/docker-compose/stored
'''
project = __load_project(path)
result = {}
if isinstance(project, dict):
return project
else:
if USE_FILTERCLASS:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, OneOffFilter.only),
key=attrgetter('name'))
else:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, one_off=True),
key=attrgetter('name'))
for container in containers:
command = container.human_readable_command
if len(command) > 30:
command = '{0} ...'.format(command[:26])
result[container.name] = {
'id': container.id,
'name': container.name,
'command': command,
'state': container.human_readable_state,
'ports': container.human_readable_ports,
}
return __standardize_result(True, 'Listing docker-compose containers', result, None)
def up(path, service_names=None):
'''
Create and start containers defined in the docker-compose.yml file
located in path, service_names is a python list, if omitted create and
start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will create and start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.up /path/where/docker-compose/stored
salt myminion dockercompose.up /path/where/docker-compose/stored '[janus]'
'''
debug_ret = {}
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
result = _get_convergence_plans(project, service_names)
ret = project.up(service_names)
if debug:
for container in ret:
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Adding containers via docker-compose', result, debug_ret)
def service_create(path, service_name, definition):
'''
Create the definition of a docker-compose service
This fails when the service already exists
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service {0} created'.format(service_name),
already_existed=True)
def service_upsert(path, service_name, definition):
'''
Create or update the definition of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_upsert /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service definition for {0} is set'.format(service_name),
already_existed=True)
def service_remove(path, service_name):
'''
Remove the definition of a docker-compose service
This does not rm the container
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_remove /path/where/docker-compose/stored service_name
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
del services[service_name]
return __dump_compose_file(path, compose_result,
'Service {0} is removed from {1}'.format(service_name, path),
already_existed=True)
def service_set_tag(path, service_name, tag):
'''
Change the tag of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
tag
Name of the tag (often used as version) that the service image should have
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name tag
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
if 'image' not in services[service_name]:
return __standardize_result(False,
'Service {0} did not contain the variable "image"'.format(service_name),
None, None)
image = services[service_name]['image'].split(':')[0]
services[service_name]['image'] = '{0}:{1}'.format(image, tag)
return __dump_compose_file(path, compose_result,
'Service {0} is set to tag "{1}"'.format(service_name, tag),
already_existed=True)
|
saltstack/salt
|
salt/modules/dockercompose.py
|
__load_project
|
python
|
def __load_project(path):
'''
Load a docker-compose project from path
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return __standardize_result(False,
msg,
None, None)
return __load_project_from_file_path(file_path)
|
Load a docker-compose project from path
:param path:
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockercompose.py#L318-L331
|
[
"def __standardize_result(status, message, data=None, debug_msg=None):\n '''\n Standardizes all responses\n\n :param status:\n :param message:\n :param data:\n :param debug_msg:\n :return:\n '''\n result = {\n 'status': status,\n 'message': message\n }\n\n if data is not None:\n result['return'] = data\n\n if debug_msg is not None and debug:\n result['debug'] = debug_msg\n\n return result\n",
"def __get_docker_file_path(path):\n '''\n Determines the filepath to use\n\n :param path:\n :return:\n '''\n if os.path.isfile(path):\n return path\n for dc_filename in DEFAULT_DC_FILENAMES:\n file_path = os.path.join(path, dc_filename)\n if os.path.isfile(file_path):\n return file_path\n",
"def __load_project_from_file_path(file_path):\n '''\n Load a docker-compose project from file path\n\n :param path:\n :return:\n '''\n try:\n project = get_project(project_dir=os.path.dirname(file_path),\n config_path=[os.path.basename(file_path)])\n except Exception as inst:\n return __handle_except(inst)\n return project\n"
] |
# -*- coding: utf-8 -*-
'''
Module to import docker-compose via saltstack
.. versionadded:: 2016.3.0
:maintainer: Jean Praloran <jeanpralo@gmail.com>
:maturity: new
:depends: docker-compose>=1.5
:platform: all
Introduction
------------
This module allows one to deal with docker-compose file in a directory.
This is a first version only, the following commands are missing at the moment
but will be built later on if the community is interested in this module:
- run
- logs
- port
- scale
Installation Prerequisites
--------------------------
This execution module requires at least version 1.4.0 of both docker-compose_ and
Docker_. docker-compose can easily be installed using :py:func:`pip.install
<salt.modules.pip.install>`:
.. code-block:: bash
salt myminion pip.install docker-compose>=1.5.0
.. _docker-compose: https://pypi.python.org/pypi/docker-compose
.. _Docker: https://www.docker.com/
How to use this module?
-----------------------
In order to use the module if you have no docker-compose file on the server you
can issue the command create, it takes two arguments the path where the
docker-compose.yml will be stored and the content of this latter:
.. code-block:: text
# salt-call -l debug dockercompose.create /tmp/toto '
database:
image: mongo:3.0
command: mongod --smallfiles --quiet --logpath=/dev/null
'
Then you can execute a list of method defined at the bottom with at least one
argument (the path where the docker-compose.yml will be read) and an optional
python list which corresponds to the services names:
.. code-block:: bash
# salt-call -l debug dockercompose.up /tmp/toto
# salt-call -l debug dockercompose.restart /tmp/toto '[database]'
# salt-call -l debug dockercompose.stop /tmp/toto
# salt-call -l debug dockercompose.rm /tmp/toto
Docker-compose method supported
-------------------------------
- up
- restart
- stop
- start
- pause
- unpause
- kill
- rm
- ps
- pull
- build
Functions
---------
- docker-compose.yml management
- :py:func:`dockercompose.create <salt.modules.dockercompose.create>`
- :py:func:`dockercompose.get <salt.modules.dockercompose.get>`
- Manage containers
- :py:func:`dockercompose.restart <salt.modules.dockercompose.restart>`
- :py:func:`dockercompose.stop <salt.modules.dockercompose.stop>`
- :py:func:`dockercompose.pause <salt.modules.dockercompose.pause>`
- :py:func:`dockercompose.unpause <salt.modules.dockercompose.unpause>`
- :py:func:`dockercompose.start <salt.modules.dockercompose.start>`
- :py:func:`dockercompose.kill <salt.modules.dockercompose.kill>`
- :py:func:`dockercompose.rm <salt.modules.dockercompose.rm>`
- :py:func:`dockercompose.up <salt.modules.dockercompose.up>`
- Manage containers image:
- :py:func:`dockercompose.pull <salt.modules.dockercompose.pull>`
- :py:func:`dockercompose.build <salt.modules.dockercompose.build>`
- Gather information about containers:
- :py:func:`dockercompose.ps <salt.modules.dockercompose.ps>`
- Manage service definitions:
- :py:func:`dockercompose.service_create <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_upsert <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_remove <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_set_tag <salt.modules.dockercompose.ps>`
Detailed Function Documentation
-------------------------------
'''
from __future__ import absolute_import, print_function, unicode_literals
import inspect
import logging
import os
import re
import salt.utils.files
import salt.utils.stringutils
from salt.ext import six
from operator import attrgetter
from salt.serializers import json
from salt.utils import yaml
try:
import compose
from compose.cli.command import get_project
from compose.service import ConvergenceStrategy
HAS_DOCKERCOMPOSE = True
except ImportError:
HAS_DOCKERCOMPOSE = False
try:
from compose.project import OneOffFilter
USE_FILTERCLASS = True
except ImportError:
USE_FILTERCLASS = False
MIN_DOCKERCOMPOSE = (1, 5, 0)
VERSION_RE = r'([\d.]+)'
log = logging.getLogger(__name__)
debug = False
__virtualname__ = 'dockercompose'
DEFAULT_DC_FILENAMES = ('docker-compose.yml', 'docker-compose.yaml')
def __virtual__():
if HAS_DOCKERCOMPOSE:
match = re.match(VERSION_RE, six.text_type(compose.__version__))
if match:
version = tuple([int(x) for x in match.group(1).split('.')])
if version >= MIN_DOCKERCOMPOSE:
return __virtualname__
return (False, 'The dockercompose execution module not loaded: '
'compose python library not available.')
def __standardize_result(status, message, data=None, debug_msg=None):
'''
Standardizes all responses
:param status:
:param message:
:param data:
:param debug_msg:
:return:
'''
result = {
'status': status,
'message': message
}
if data is not None:
result['return'] = data
if debug_msg is not None and debug:
result['debug'] = debug_msg
return result
def __get_docker_file_path(path):
'''
Determines the filepath to use
:param path:
:return:
'''
if os.path.isfile(path):
return path
for dc_filename in DEFAULT_DC_FILENAMES:
file_path = os.path.join(path, dc_filename)
if os.path.isfile(file_path):
return file_path
# implicitly return None
def __read_docker_compose_file(file_path):
'''
Read the compose file if it exists in the directory
:param file_path:
:return:
'''
if not os.path.isfile(file_path):
return __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
file_name = os.path.basename(file_path)
result = {file_name: ''}
for line in fl:
result[file_name] += salt.utils.stringutils.to_unicode(line)
except EnvironmentError:
return __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
return __standardize_result(True,
'Reading content of {0}'.format(file_path),
result, None)
def __load_docker_compose(path):
'''
Read the compose file and load its' contents
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return None, __standardize_result(False, msg,
None, None)
if not os.path.isfile(file_path):
return None, __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
loaded = yaml.load(fl)
except EnvironmentError:
return None, __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(file_path, yerr)
return None, __standardize_result(False, msg,
None, None)
if not loaded:
msg = 'Got empty compose file at {0}'.format(file_path)
return None, __standardize_result(False, msg,
None, None)
if 'services' not in loaded:
loaded['services'] = {}
result = {
'compose_content': loaded,
'file_name': os.path.basename(file_path)
}
return result, None
def __dump_docker_compose(path, content, already_existed):
'''
Dumps
:param path:
:param content: the not-yet dumped content
:return:
'''
try:
dumped = yaml.safe_dump(content, indent=2, default_flow_style=False)
return __write_docker_compose(path, dumped, already_existed)
except TypeError as t_err:
msg = 'Could not dump {0} {1}'.format(content, t_err)
return __standardize_result(False, msg,
None, None)
def __write_docker_compose(path, docker_compose, already_existed):
'''
Write docker-compose to a path
in order to use it with docker-compose ( config check )
:param path:
docker_compose
contains the docker-compose file
:return:
'''
if path.lower().endswith(('.yml', '.yaml')):
file_path = path
dir_name = os.path.dirname(path)
else:
dir_name = path
file_path = os.path.join(dir_name, DEFAULT_DC_FILENAMES[0])
if os.path.isdir(dir_name) is False:
os.mkdir(dir_name)
try:
with salt.utils.files.fopen(file_path, 'w') as fl:
fl.write(salt.utils.stringutils.to_str(docker_compose))
except EnvironmentError:
return __standardize_result(False,
'Could not write {0}'.format(file_path),
None, None)
project = __load_project_from_file_path(file_path)
if isinstance(project, dict):
if not already_existed:
os.remove(file_path)
return project
return file_path
def __load_project_from_file_path(file_path):
'''
Load a docker-compose project from file path
:param path:
:return:
'''
try:
project = get_project(project_dir=os.path.dirname(file_path),
config_path=[os.path.basename(file_path)])
except Exception as inst:
return __handle_except(inst)
return project
def __load_compose_definitions(path, definition):
'''
Will load the compose file located at path
Then determines the format/contents of the sent definition
err or results are only set if there were any
:param path:
:param definition:
:return tuple(compose_result, loaded_definition, err):
'''
compose_result, err = __load_docker_compose(path)
if err:
return None, None, err
if isinstance(definition, dict):
return compose_result, definition, None
elif definition.strip().startswith('{'):
try:
loaded_definition = json.deserialize(definition)
except json.DeserializationError as jerr:
msg = 'Could not parse {0} {1}'.format(definition, jerr)
return None, None, __standardize_result(False, msg,
None, None)
else:
try:
loaded_definition = yaml.load(definition)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(definition, yerr)
return None, None, __standardize_result(False, msg,
None, None)
return compose_result, loaded_definition, None
def __dump_compose_file(path, compose_result, success_msg, already_existed):
'''
Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return:
'''
ret = __dump_docker_compose(path,
compose_result['compose_content'],
already_existed)
if isinstance(ret, dict):
return ret
return __standardize_result(True, success_msg,
compose_result['compose_content'], None)
def __handle_except(inst):
'''
Handle exception and return a standard result
:param inst:
:return:
'''
return __standardize_result(False,
'Docker-compose command {0} failed'.
format(inspect.stack()[1][3]),
'{0}'.format(inst), None)
def _get_convergence_plans(project, service_names):
'''
Get action executed for each container
:param project:
:param service_names:
:return:
'''
ret = {}
plans = project._get_convergence_plans(project.get_services(service_names),
ConvergenceStrategy.changed)
for cont in plans:
(action, container) = plans[cont]
if action == 'create':
ret[cont] = 'Creating container'
elif action == 'recreate':
ret[cont] = 'Re-creating container'
elif action == 'start':
ret[cont] = 'Starting container'
elif action == 'noop':
ret[cont] = 'Container is up to date'
return ret
def get(path):
'''
Get the content of the docker-compose file into a directory
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.get /path/where/docker-compose/stored
'''
file_path = __get_docker_file_path(path)
if file_path is None:
return __standardize_result(False,
'Path {} is not present'.format(path),
None, None)
salt_result = __read_docker_compose_file(file_path)
if not salt_result['status']:
return salt_result
project = __load_project(path)
if isinstance(project, dict):
salt_result['return']['valid'] = False
else:
salt_result['return']['valid'] = True
return salt_result
def create(path, docker_compose):
'''
Create and validate a docker-compose file into a directory
path
Path where the docker-compose file will be stored on the server
docker_compose
docker_compose file
CLI Example:
.. code-block:: bash
salt myminion dockercompose.create /path/where/docker-compose/stored content
'''
if docker_compose:
ret = __write_docker_compose(path,
docker_compose,
already_existed=False)
if isinstance(ret, dict):
return ret
else:
return __standardize_result(False,
'Creating a docker-compose project failed, you must send a valid docker-compose file',
None, None)
return __standardize_result(True,
'Successfully created the docker-compose file',
{'compose.base_dir': path},
None)
def pull(path, service_names=None):
'''
Pull image for containers in the docker-compose file, service_names is a
python list, if omitted pull all images
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pull /path/where/docker-compose/stored
salt myminion dockercompose.pull /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.pull(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pulling containers images via docker-compose succeeded',
None, None)
def build(path, service_names=None):
'''
Build image for containers in the docker-compose file, service_names is a
python list, if omitted build images for all containers. Please note
that at the moment the module does not allow you to upload your Dockerfile,
nor any other file you could need with your docker-compose.yml, you will
have to make sure the files you need are actually in the directory specified
in the `build` keyword
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.build /path/where/docker-compose/stored
salt myminion dockercompose.build /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.build(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Building containers images via docker-compose succeeded',
None, None)
def restart(path, service_names=None):
'''
Restart container(s) in the docker-compose file, service_names is a python
list, if omitted restart all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will restart only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.restart /path/where/docker-compose/stored
salt myminion dockercompose.restart /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.restart(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'restarted'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Restarting containers via docker-compose', result, debug_ret)
def stop(path, service_names=None):
'''
Stop running containers in the docker-compose file, service_names is a python
list, if omitted stop all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will stop only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.stop /path/where/docker-compose/stored
salt myminion dockercompose.stop /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
def pause(path, service_names=None):
'''
Pause running containers in the docker-compose file, service_names is a python
list, if omitted pause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.pause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'paused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pausing containers via docker-compose', result, debug_ret)
def unpause(path, service_names=None):
'''
Un-Pause containers in the docker-compose file, service_names is a python
list, if omitted unpause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will un-pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.unpause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'unpaused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Un-Pausing containers via docker-compose', result, debug_ret)
def start(path, service_names=None):
'''
Start containers in the docker-compose file, service_names is a python
list, if omitted start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.start /path/where/docker-compose/stored
salt myminion dockercompose.start /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.start(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'started'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Starting containers via docker-compose', result, debug_ret)
def kill(path, service_names=None):
'''
Kill containers in the docker-compose file, service_names is a python
list, if omitted kill all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will kill only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.kill /path/where/docker-compose/stored
salt myminion dockercompose.kill /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.kill(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'killed'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Killing containers via docker-compose', result, debug_ret)
def rm(path, service_names=None):
'''
Remove stopped containers in the docker-compose file, service_names is a python
list, if omitted remove all stopped containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will remove only the specified stopped services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.rm /path/where/docker-compose/stored
salt myminion dockercompose.rm /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.remove_stopped(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Removing stopped containers via docker-compose', None, None)
def ps(path):
'''
List all running containers and report some information about them
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.ps /path/where/docker-compose/stored
'''
project = __load_project(path)
result = {}
if isinstance(project, dict):
return project
else:
if USE_FILTERCLASS:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, OneOffFilter.only),
key=attrgetter('name'))
else:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, one_off=True),
key=attrgetter('name'))
for container in containers:
command = container.human_readable_command
if len(command) > 30:
command = '{0} ...'.format(command[:26])
result[container.name] = {
'id': container.id,
'name': container.name,
'command': command,
'state': container.human_readable_state,
'ports': container.human_readable_ports,
}
return __standardize_result(True, 'Listing docker-compose containers', result, None)
def up(path, service_names=None):
'''
Create and start containers defined in the docker-compose.yml file
located in path, service_names is a python list, if omitted create and
start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will create and start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.up /path/where/docker-compose/stored
salt myminion dockercompose.up /path/where/docker-compose/stored '[janus]'
'''
debug_ret = {}
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
result = _get_convergence_plans(project, service_names)
ret = project.up(service_names)
if debug:
for container in ret:
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Adding containers via docker-compose', result, debug_ret)
def service_create(path, service_name, definition):
'''
Create the definition of a docker-compose service
This fails when the service already exists
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service {0} created'.format(service_name),
already_existed=True)
def service_upsert(path, service_name, definition):
'''
Create or update the definition of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_upsert /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service definition for {0} is set'.format(service_name),
already_existed=True)
def service_remove(path, service_name):
'''
Remove the definition of a docker-compose service
This does not rm the container
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_remove /path/where/docker-compose/stored service_name
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
del services[service_name]
return __dump_compose_file(path, compose_result,
'Service {0} is removed from {1}'.format(service_name, path),
already_existed=True)
def service_set_tag(path, service_name, tag):
'''
Change the tag of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
tag
Name of the tag (often used as version) that the service image should have
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name tag
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
if 'image' not in services[service_name]:
return __standardize_result(False,
'Service {0} did not contain the variable "image"'.format(service_name),
None, None)
image = services[service_name]['image'].split(':')[0]
services[service_name]['image'] = '{0}:{1}'.format(image, tag)
return __dump_compose_file(path, compose_result,
'Service {0} is set to tag "{1}"'.format(service_name, tag),
already_existed=True)
|
saltstack/salt
|
salt/modules/dockercompose.py
|
__load_project_from_file_path
|
python
|
def __load_project_from_file_path(file_path):
'''
Load a docker-compose project from file path
:param path:
:return:
'''
try:
project = get_project(project_dir=os.path.dirname(file_path),
config_path=[os.path.basename(file_path)])
except Exception as inst:
return __handle_except(inst)
return project
|
Load a docker-compose project from file path
:param path:
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockercompose.py#L334-L346
| null |
# -*- coding: utf-8 -*-
'''
Module to import docker-compose via saltstack
.. versionadded:: 2016.3.0
:maintainer: Jean Praloran <jeanpralo@gmail.com>
:maturity: new
:depends: docker-compose>=1.5
:platform: all
Introduction
------------
This module allows one to deal with docker-compose file in a directory.
This is a first version only, the following commands are missing at the moment
but will be built later on if the community is interested in this module:
- run
- logs
- port
- scale
Installation Prerequisites
--------------------------
This execution module requires at least version 1.4.0 of both docker-compose_ and
Docker_. docker-compose can easily be installed using :py:func:`pip.install
<salt.modules.pip.install>`:
.. code-block:: bash
salt myminion pip.install docker-compose>=1.5.0
.. _docker-compose: https://pypi.python.org/pypi/docker-compose
.. _Docker: https://www.docker.com/
How to use this module?
-----------------------
In order to use the module if you have no docker-compose file on the server you
can issue the command create, it takes two arguments the path where the
docker-compose.yml will be stored and the content of this latter:
.. code-block:: text
# salt-call -l debug dockercompose.create /tmp/toto '
database:
image: mongo:3.0
command: mongod --smallfiles --quiet --logpath=/dev/null
'
Then you can execute a list of method defined at the bottom with at least one
argument (the path where the docker-compose.yml will be read) and an optional
python list which corresponds to the services names:
.. code-block:: bash
# salt-call -l debug dockercompose.up /tmp/toto
# salt-call -l debug dockercompose.restart /tmp/toto '[database]'
# salt-call -l debug dockercompose.stop /tmp/toto
# salt-call -l debug dockercompose.rm /tmp/toto
Docker-compose method supported
-------------------------------
- up
- restart
- stop
- start
- pause
- unpause
- kill
- rm
- ps
- pull
- build
Functions
---------
- docker-compose.yml management
- :py:func:`dockercompose.create <salt.modules.dockercompose.create>`
- :py:func:`dockercompose.get <salt.modules.dockercompose.get>`
- Manage containers
- :py:func:`dockercompose.restart <salt.modules.dockercompose.restart>`
- :py:func:`dockercompose.stop <salt.modules.dockercompose.stop>`
- :py:func:`dockercompose.pause <salt.modules.dockercompose.pause>`
- :py:func:`dockercompose.unpause <salt.modules.dockercompose.unpause>`
- :py:func:`dockercompose.start <salt.modules.dockercompose.start>`
- :py:func:`dockercompose.kill <salt.modules.dockercompose.kill>`
- :py:func:`dockercompose.rm <salt.modules.dockercompose.rm>`
- :py:func:`dockercompose.up <salt.modules.dockercompose.up>`
- Manage containers image:
- :py:func:`dockercompose.pull <salt.modules.dockercompose.pull>`
- :py:func:`dockercompose.build <salt.modules.dockercompose.build>`
- Gather information about containers:
- :py:func:`dockercompose.ps <salt.modules.dockercompose.ps>`
- Manage service definitions:
- :py:func:`dockercompose.service_create <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_upsert <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_remove <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_set_tag <salt.modules.dockercompose.ps>`
Detailed Function Documentation
-------------------------------
'''
from __future__ import absolute_import, print_function, unicode_literals
import inspect
import logging
import os
import re
import salt.utils.files
import salt.utils.stringutils
from salt.ext import six
from operator import attrgetter
from salt.serializers import json
from salt.utils import yaml
try:
import compose
from compose.cli.command import get_project
from compose.service import ConvergenceStrategy
HAS_DOCKERCOMPOSE = True
except ImportError:
HAS_DOCKERCOMPOSE = False
try:
from compose.project import OneOffFilter
USE_FILTERCLASS = True
except ImportError:
USE_FILTERCLASS = False
MIN_DOCKERCOMPOSE = (1, 5, 0)
VERSION_RE = r'([\d.]+)'
log = logging.getLogger(__name__)
debug = False
__virtualname__ = 'dockercompose'
DEFAULT_DC_FILENAMES = ('docker-compose.yml', 'docker-compose.yaml')
def __virtual__():
if HAS_DOCKERCOMPOSE:
match = re.match(VERSION_RE, six.text_type(compose.__version__))
if match:
version = tuple([int(x) for x in match.group(1).split('.')])
if version >= MIN_DOCKERCOMPOSE:
return __virtualname__
return (False, 'The dockercompose execution module not loaded: '
'compose python library not available.')
def __standardize_result(status, message, data=None, debug_msg=None):
'''
Standardizes all responses
:param status:
:param message:
:param data:
:param debug_msg:
:return:
'''
result = {
'status': status,
'message': message
}
if data is not None:
result['return'] = data
if debug_msg is not None and debug:
result['debug'] = debug_msg
return result
def __get_docker_file_path(path):
'''
Determines the filepath to use
:param path:
:return:
'''
if os.path.isfile(path):
return path
for dc_filename in DEFAULT_DC_FILENAMES:
file_path = os.path.join(path, dc_filename)
if os.path.isfile(file_path):
return file_path
# implicitly return None
def __read_docker_compose_file(file_path):
'''
Read the compose file if it exists in the directory
:param file_path:
:return:
'''
if not os.path.isfile(file_path):
return __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
file_name = os.path.basename(file_path)
result = {file_name: ''}
for line in fl:
result[file_name] += salt.utils.stringutils.to_unicode(line)
except EnvironmentError:
return __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
return __standardize_result(True,
'Reading content of {0}'.format(file_path),
result, None)
def __load_docker_compose(path):
'''
Read the compose file and load its' contents
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return None, __standardize_result(False, msg,
None, None)
if not os.path.isfile(file_path):
return None, __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
loaded = yaml.load(fl)
except EnvironmentError:
return None, __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(file_path, yerr)
return None, __standardize_result(False, msg,
None, None)
if not loaded:
msg = 'Got empty compose file at {0}'.format(file_path)
return None, __standardize_result(False, msg,
None, None)
if 'services' not in loaded:
loaded['services'] = {}
result = {
'compose_content': loaded,
'file_name': os.path.basename(file_path)
}
return result, None
def __dump_docker_compose(path, content, already_existed):
'''
Dumps
:param path:
:param content: the not-yet dumped content
:return:
'''
try:
dumped = yaml.safe_dump(content, indent=2, default_flow_style=False)
return __write_docker_compose(path, dumped, already_existed)
except TypeError as t_err:
msg = 'Could not dump {0} {1}'.format(content, t_err)
return __standardize_result(False, msg,
None, None)
def __write_docker_compose(path, docker_compose, already_existed):
'''
Write docker-compose to a path
in order to use it with docker-compose ( config check )
:param path:
docker_compose
contains the docker-compose file
:return:
'''
if path.lower().endswith(('.yml', '.yaml')):
file_path = path
dir_name = os.path.dirname(path)
else:
dir_name = path
file_path = os.path.join(dir_name, DEFAULT_DC_FILENAMES[0])
if os.path.isdir(dir_name) is False:
os.mkdir(dir_name)
try:
with salt.utils.files.fopen(file_path, 'w') as fl:
fl.write(salt.utils.stringutils.to_str(docker_compose))
except EnvironmentError:
return __standardize_result(False,
'Could not write {0}'.format(file_path),
None, None)
project = __load_project_from_file_path(file_path)
if isinstance(project, dict):
if not already_existed:
os.remove(file_path)
return project
return file_path
def __load_project(path):
'''
Load a docker-compose project from path
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return __standardize_result(False,
msg,
None, None)
return __load_project_from_file_path(file_path)
def __load_compose_definitions(path, definition):
'''
Will load the compose file located at path
Then determines the format/contents of the sent definition
err or results are only set if there were any
:param path:
:param definition:
:return tuple(compose_result, loaded_definition, err):
'''
compose_result, err = __load_docker_compose(path)
if err:
return None, None, err
if isinstance(definition, dict):
return compose_result, definition, None
elif definition.strip().startswith('{'):
try:
loaded_definition = json.deserialize(definition)
except json.DeserializationError as jerr:
msg = 'Could not parse {0} {1}'.format(definition, jerr)
return None, None, __standardize_result(False, msg,
None, None)
else:
try:
loaded_definition = yaml.load(definition)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(definition, yerr)
return None, None, __standardize_result(False, msg,
None, None)
return compose_result, loaded_definition, None
def __dump_compose_file(path, compose_result, success_msg, already_existed):
'''
Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return:
'''
ret = __dump_docker_compose(path,
compose_result['compose_content'],
already_existed)
if isinstance(ret, dict):
return ret
return __standardize_result(True, success_msg,
compose_result['compose_content'], None)
def __handle_except(inst):
'''
Handle exception and return a standard result
:param inst:
:return:
'''
return __standardize_result(False,
'Docker-compose command {0} failed'.
format(inspect.stack()[1][3]),
'{0}'.format(inst), None)
def _get_convergence_plans(project, service_names):
'''
Get action executed for each container
:param project:
:param service_names:
:return:
'''
ret = {}
plans = project._get_convergence_plans(project.get_services(service_names),
ConvergenceStrategy.changed)
for cont in plans:
(action, container) = plans[cont]
if action == 'create':
ret[cont] = 'Creating container'
elif action == 'recreate':
ret[cont] = 'Re-creating container'
elif action == 'start':
ret[cont] = 'Starting container'
elif action == 'noop':
ret[cont] = 'Container is up to date'
return ret
def get(path):
'''
Get the content of the docker-compose file into a directory
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.get /path/where/docker-compose/stored
'''
file_path = __get_docker_file_path(path)
if file_path is None:
return __standardize_result(False,
'Path {} is not present'.format(path),
None, None)
salt_result = __read_docker_compose_file(file_path)
if not salt_result['status']:
return salt_result
project = __load_project(path)
if isinstance(project, dict):
salt_result['return']['valid'] = False
else:
salt_result['return']['valid'] = True
return salt_result
def create(path, docker_compose):
'''
Create and validate a docker-compose file into a directory
path
Path where the docker-compose file will be stored on the server
docker_compose
docker_compose file
CLI Example:
.. code-block:: bash
salt myminion dockercompose.create /path/where/docker-compose/stored content
'''
if docker_compose:
ret = __write_docker_compose(path,
docker_compose,
already_existed=False)
if isinstance(ret, dict):
return ret
else:
return __standardize_result(False,
'Creating a docker-compose project failed, you must send a valid docker-compose file',
None, None)
return __standardize_result(True,
'Successfully created the docker-compose file',
{'compose.base_dir': path},
None)
def pull(path, service_names=None):
'''
Pull image for containers in the docker-compose file, service_names is a
python list, if omitted pull all images
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pull /path/where/docker-compose/stored
salt myminion dockercompose.pull /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.pull(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pulling containers images via docker-compose succeeded',
None, None)
def build(path, service_names=None):
'''
Build image for containers in the docker-compose file, service_names is a
python list, if omitted build images for all containers. Please note
that at the moment the module does not allow you to upload your Dockerfile,
nor any other file you could need with your docker-compose.yml, you will
have to make sure the files you need are actually in the directory specified
in the `build` keyword
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.build /path/where/docker-compose/stored
salt myminion dockercompose.build /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.build(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Building containers images via docker-compose succeeded',
None, None)
def restart(path, service_names=None):
'''
Restart container(s) in the docker-compose file, service_names is a python
list, if omitted restart all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will restart only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.restart /path/where/docker-compose/stored
salt myminion dockercompose.restart /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.restart(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'restarted'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Restarting containers via docker-compose', result, debug_ret)
def stop(path, service_names=None):
'''
Stop running containers in the docker-compose file, service_names is a python
list, if omitted stop all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will stop only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.stop /path/where/docker-compose/stored
salt myminion dockercompose.stop /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
def pause(path, service_names=None):
'''
Pause running containers in the docker-compose file, service_names is a python
list, if omitted pause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.pause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'paused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pausing containers via docker-compose', result, debug_ret)
def unpause(path, service_names=None):
'''
Un-Pause containers in the docker-compose file, service_names is a python
list, if omitted unpause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will un-pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.unpause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'unpaused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Un-Pausing containers via docker-compose', result, debug_ret)
def start(path, service_names=None):
'''
Start containers in the docker-compose file, service_names is a python
list, if omitted start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.start /path/where/docker-compose/stored
salt myminion dockercompose.start /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.start(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'started'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Starting containers via docker-compose', result, debug_ret)
def kill(path, service_names=None):
'''
Kill containers in the docker-compose file, service_names is a python
list, if omitted kill all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will kill only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.kill /path/where/docker-compose/stored
salt myminion dockercompose.kill /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.kill(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'killed'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Killing containers via docker-compose', result, debug_ret)
def rm(path, service_names=None):
'''
Remove stopped containers in the docker-compose file, service_names is a python
list, if omitted remove all stopped containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will remove only the specified stopped services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.rm /path/where/docker-compose/stored
salt myminion dockercompose.rm /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.remove_stopped(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Removing stopped containers via docker-compose', None, None)
def ps(path):
'''
List all running containers and report some information about them
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.ps /path/where/docker-compose/stored
'''
project = __load_project(path)
result = {}
if isinstance(project, dict):
return project
else:
if USE_FILTERCLASS:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, OneOffFilter.only),
key=attrgetter('name'))
else:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, one_off=True),
key=attrgetter('name'))
for container in containers:
command = container.human_readable_command
if len(command) > 30:
command = '{0} ...'.format(command[:26])
result[container.name] = {
'id': container.id,
'name': container.name,
'command': command,
'state': container.human_readable_state,
'ports': container.human_readable_ports,
}
return __standardize_result(True, 'Listing docker-compose containers', result, None)
def up(path, service_names=None):
'''
Create and start containers defined in the docker-compose.yml file
located in path, service_names is a python list, if omitted create and
start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will create and start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.up /path/where/docker-compose/stored
salt myminion dockercompose.up /path/where/docker-compose/stored '[janus]'
'''
debug_ret = {}
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
result = _get_convergence_plans(project, service_names)
ret = project.up(service_names)
if debug:
for container in ret:
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Adding containers via docker-compose', result, debug_ret)
def service_create(path, service_name, definition):
'''
Create the definition of a docker-compose service
This fails when the service already exists
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service {0} created'.format(service_name),
already_existed=True)
def service_upsert(path, service_name, definition):
'''
Create or update the definition of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_upsert /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service definition for {0} is set'.format(service_name),
already_existed=True)
def service_remove(path, service_name):
'''
Remove the definition of a docker-compose service
This does not rm the container
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_remove /path/where/docker-compose/stored service_name
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
del services[service_name]
return __dump_compose_file(path, compose_result,
'Service {0} is removed from {1}'.format(service_name, path),
already_existed=True)
def service_set_tag(path, service_name, tag):
'''
Change the tag of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
tag
Name of the tag (often used as version) that the service image should have
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name tag
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
if 'image' not in services[service_name]:
return __standardize_result(False,
'Service {0} did not contain the variable "image"'.format(service_name),
None, None)
image = services[service_name]['image'].split(':')[0]
services[service_name]['image'] = '{0}:{1}'.format(image, tag)
return __dump_compose_file(path, compose_result,
'Service {0} is set to tag "{1}"'.format(service_name, tag),
already_existed=True)
|
saltstack/salt
|
salt/modules/dockercompose.py
|
__load_compose_definitions
|
python
|
def __load_compose_definitions(path, definition):
'''
Will load the compose file located at path
Then determines the format/contents of the sent definition
err or results are only set if there were any
:param path:
:param definition:
:return tuple(compose_result, loaded_definition, err):
'''
compose_result, err = __load_docker_compose(path)
if err:
return None, None, err
if isinstance(definition, dict):
return compose_result, definition, None
elif definition.strip().startswith('{'):
try:
loaded_definition = json.deserialize(definition)
except json.DeserializationError as jerr:
msg = 'Could not parse {0} {1}'.format(definition, jerr)
return None, None, __standardize_result(False, msg,
None, None)
else:
try:
loaded_definition = yaml.load(definition)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(definition, yerr)
return None, None, __standardize_result(False, msg,
None, None)
return compose_result, loaded_definition, None
|
Will load the compose file located at path
Then determines the format/contents of the sent definition
err or results are only set if there were any
:param path:
:param definition:
:return tuple(compose_result, loaded_definition, err):
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockercompose.py#L349-L379
|
[
"def load(stream, Loader=SaltYamlSafeLoader):\n return yaml.load(stream, Loader=Loader)\n",
"def deserialize(stream_or_string, **options):\n '''\n Deserialize any string or stream like object into a Python data structure.\n\n :param stream_or_string: stream or string to deserialize.\n :param options: options given to lower json/simplejson module.\n '''\n\n try:\n if not isinstance(stream_or_string, (bytes, six.string_types)):\n return salt.utils.json.load(\n stream_or_string, _json_module=_json, **options)\n\n if isinstance(stream_or_string, bytes):\n stream_or_string = stream_or_string.decode('utf-8')\n\n return salt.utils.json.loads(stream_or_string, _json_module=_json)\n except Exception as error:\n raise DeserializationError(error)\n",
"def __standardize_result(status, message, data=None, debug_msg=None):\n '''\n Standardizes all responses\n\n :param status:\n :param message:\n :param data:\n :param debug_msg:\n :return:\n '''\n result = {\n 'status': status,\n 'message': message\n }\n\n if data is not None:\n result['return'] = data\n\n if debug_msg is not None and debug:\n result['debug'] = debug_msg\n\n return result\n",
"def __load_docker_compose(path):\n '''\n Read the compose file and load its' contents\n\n :param path:\n :return:\n '''\n file_path = __get_docker_file_path(path)\n if file_path is None:\n msg = 'Could not find docker-compose file at {0}'.format(path)\n return None, __standardize_result(False, msg,\n None, None)\n if not os.path.isfile(file_path):\n return None, __standardize_result(False,\n 'Path {} is not present'.format(file_path),\n None, None)\n try:\n with salt.utils.files.fopen(file_path, 'r') as fl:\n loaded = yaml.load(fl)\n except EnvironmentError:\n return None, __standardize_result(False,\n 'Could not read {0}'.format(file_path),\n None, None)\n except yaml.YAMLError as yerr:\n msg = 'Could not parse {0} {1}'.format(file_path, yerr)\n return None, __standardize_result(False, msg,\n None, None)\n if not loaded:\n msg = 'Got empty compose file at {0}'.format(file_path)\n return None, __standardize_result(False, msg,\n None, None)\n if 'services' not in loaded:\n loaded['services'] = {}\n result = {\n 'compose_content': loaded,\n 'file_name': os.path.basename(file_path)\n }\n return result, None\n"
] |
# -*- coding: utf-8 -*-
'''
Module to import docker-compose via saltstack
.. versionadded:: 2016.3.0
:maintainer: Jean Praloran <jeanpralo@gmail.com>
:maturity: new
:depends: docker-compose>=1.5
:platform: all
Introduction
------------
This module allows one to deal with docker-compose file in a directory.
This is a first version only, the following commands are missing at the moment
but will be built later on if the community is interested in this module:
- run
- logs
- port
- scale
Installation Prerequisites
--------------------------
This execution module requires at least version 1.4.0 of both docker-compose_ and
Docker_. docker-compose can easily be installed using :py:func:`pip.install
<salt.modules.pip.install>`:
.. code-block:: bash
salt myminion pip.install docker-compose>=1.5.0
.. _docker-compose: https://pypi.python.org/pypi/docker-compose
.. _Docker: https://www.docker.com/
How to use this module?
-----------------------
In order to use the module if you have no docker-compose file on the server you
can issue the command create, it takes two arguments the path where the
docker-compose.yml will be stored and the content of this latter:
.. code-block:: text
# salt-call -l debug dockercompose.create /tmp/toto '
database:
image: mongo:3.0
command: mongod --smallfiles --quiet --logpath=/dev/null
'
Then you can execute a list of method defined at the bottom with at least one
argument (the path where the docker-compose.yml will be read) and an optional
python list which corresponds to the services names:
.. code-block:: bash
# salt-call -l debug dockercompose.up /tmp/toto
# salt-call -l debug dockercompose.restart /tmp/toto '[database]'
# salt-call -l debug dockercompose.stop /tmp/toto
# salt-call -l debug dockercompose.rm /tmp/toto
Docker-compose method supported
-------------------------------
- up
- restart
- stop
- start
- pause
- unpause
- kill
- rm
- ps
- pull
- build
Functions
---------
- docker-compose.yml management
- :py:func:`dockercompose.create <salt.modules.dockercompose.create>`
- :py:func:`dockercompose.get <salt.modules.dockercompose.get>`
- Manage containers
- :py:func:`dockercompose.restart <salt.modules.dockercompose.restart>`
- :py:func:`dockercompose.stop <salt.modules.dockercompose.stop>`
- :py:func:`dockercompose.pause <salt.modules.dockercompose.pause>`
- :py:func:`dockercompose.unpause <salt.modules.dockercompose.unpause>`
- :py:func:`dockercompose.start <salt.modules.dockercompose.start>`
- :py:func:`dockercompose.kill <salt.modules.dockercompose.kill>`
- :py:func:`dockercompose.rm <salt.modules.dockercompose.rm>`
- :py:func:`dockercompose.up <salt.modules.dockercompose.up>`
- Manage containers image:
- :py:func:`dockercompose.pull <salt.modules.dockercompose.pull>`
- :py:func:`dockercompose.build <salt.modules.dockercompose.build>`
- Gather information about containers:
- :py:func:`dockercompose.ps <salt.modules.dockercompose.ps>`
- Manage service definitions:
- :py:func:`dockercompose.service_create <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_upsert <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_remove <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_set_tag <salt.modules.dockercompose.ps>`
Detailed Function Documentation
-------------------------------
'''
from __future__ import absolute_import, print_function, unicode_literals
import inspect
import logging
import os
import re
import salt.utils.files
import salt.utils.stringutils
from salt.ext import six
from operator import attrgetter
from salt.serializers import json
from salt.utils import yaml
try:
import compose
from compose.cli.command import get_project
from compose.service import ConvergenceStrategy
HAS_DOCKERCOMPOSE = True
except ImportError:
HAS_DOCKERCOMPOSE = False
try:
from compose.project import OneOffFilter
USE_FILTERCLASS = True
except ImportError:
USE_FILTERCLASS = False
MIN_DOCKERCOMPOSE = (1, 5, 0)
VERSION_RE = r'([\d.]+)'
log = logging.getLogger(__name__)
debug = False
__virtualname__ = 'dockercompose'
DEFAULT_DC_FILENAMES = ('docker-compose.yml', 'docker-compose.yaml')
def __virtual__():
if HAS_DOCKERCOMPOSE:
match = re.match(VERSION_RE, six.text_type(compose.__version__))
if match:
version = tuple([int(x) for x in match.group(1).split('.')])
if version >= MIN_DOCKERCOMPOSE:
return __virtualname__
return (False, 'The dockercompose execution module not loaded: '
'compose python library not available.')
def __standardize_result(status, message, data=None, debug_msg=None):
'''
Standardizes all responses
:param status:
:param message:
:param data:
:param debug_msg:
:return:
'''
result = {
'status': status,
'message': message
}
if data is not None:
result['return'] = data
if debug_msg is not None and debug:
result['debug'] = debug_msg
return result
def __get_docker_file_path(path):
'''
Determines the filepath to use
:param path:
:return:
'''
if os.path.isfile(path):
return path
for dc_filename in DEFAULT_DC_FILENAMES:
file_path = os.path.join(path, dc_filename)
if os.path.isfile(file_path):
return file_path
# implicitly return None
def __read_docker_compose_file(file_path):
'''
Read the compose file if it exists in the directory
:param file_path:
:return:
'''
if not os.path.isfile(file_path):
return __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
file_name = os.path.basename(file_path)
result = {file_name: ''}
for line in fl:
result[file_name] += salt.utils.stringutils.to_unicode(line)
except EnvironmentError:
return __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
return __standardize_result(True,
'Reading content of {0}'.format(file_path),
result, None)
def __load_docker_compose(path):
'''
Read the compose file and load its' contents
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return None, __standardize_result(False, msg,
None, None)
if not os.path.isfile(file_path):
return None, __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
loaded = yaml.load(fl)
except EnvironmentError:
return None, __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(file_path, yerr)
return None, __standardize_result(False, msg,
None, None)
if not loaded:
msg = 'Got empty compose file at {0}'.format(file_path)
return None, __standardize_result(False, msg,
None, None)
if 'services' not in loaded:
loaded['services'] = {}
result = {
'compose_content': loaded,
'file_name': os.path.basename(file_path)
}
return result, None
def __dump_docker_compose(path, content, already_existed):
'''
Dumps
:param path:
:param content: the not-yet dumped content
:return:
'''
try:
dumped = yaml.safe_dump(content, indent=2, default_flow_style=False)
return __write_docker_compose(path, dumped, already_existed)
except TypeError as t_err:
msg = 'Could not dump {0} {1}'.format(content, t_err)
return __standardize_result(False, msg,
None, None)
def __write_docker_compose(path, docker_compose, already_existed):
'''
Write docker-compose to a path
in order to use it with docker-compose ( config check )
:param path:
docker_compose
contains the docker-compose file
:return:
'''
if path.lower().endswith(('.yml', '.yaml')):
file_path = path
dir_name = os.path.dirname(path)
else:
dir_name = path
file_path = os.path.join(dir_name, DEFAULT_DC_FILENAMES[0])
if os.path.isdir(dir_name) is False:
os.mkdir(dir_name)
try:
with salt.utils.files.fopen(file_path, 'w') as fl:
fl.write(salt.utils.stringutils.to_str(docker_compose))
except EnvironmentError:
return __standardize_result(False,
'Could not write {0}'.format(file_path),
None, None)
project = __load_project_from_file_path(file_path)
if isinstance(project, dict):
if not already_existed:
os.remove(file_path)
return project
return file_path
def __load_project(path):
'''
Load a docker-compose project from path
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return __standardize_result(False,
msg,
None, None)
return __load_project_from_file_path(file_path)
def __load_project_from_file_path(file_path):
'''
Load a docker-compose project from file path
:param path:
:return:
'''
try:
project = get_project(project_dir=os.path.dirname(file_path),
config_path=[os.path.basename(file_path)])
except Exception as inst:
return __handle_except(inst)
return project
def __dump_compose_file(path, compose_result, success_msg, already_existed):
'''
Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return:
'''
ret = __dump_docker_compose(path,
compose_result['compose_content'],
already_existed)
if isinstance(ret, dict):
return ret
return __standardize_result(True, success_msg,
compose_result['compose_content'], None)
def __handle_except(inst):
'''
Handle exception and return a standard result
:param inst:
:return:
'''
return __standardize_result(False,
'Docker-compose command {0} failed'.
format(inspect.stack()[1][3]),
'{0}'.format(inst), None)
def _get_convergence_plans(project, service_names):
'''
Get action executed for each container
:param project:
:param service_names:
:return:
'''
ret = {}
plans = project._get_convergence_plans(project.get_services(service_names),
ConvergenceStrategy.changed)
for cont in plans:
(action, container) = plans[cont]
if action == 'create':
ret[cont] = 'Creating container'
elif action == 'recreate':
ret[cont] = 'Re-creating container'
elif action == 'start':
ret[cont] = 'Starting container'
elif action == 'noop':
ret[cont] = 'Container is up to date'
return ret
def get(path):
'''
Get the content of the docker-compose file into a directory
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.get /path/where/docker-compose/stored
'''
file_path = __get_docker_file_path(path)
if file_path is None:
return __standardize_result(False,
'Path {} is not present'.format(path),
None, None)
salt_result = __read_docker_compose_file(file_path)
if not salt_result['status']:
return salt_result
project = __load_project(path)
if isinstance(project, dict):
salt_result['return']['valid'] = False
else:
salt_result['return']['valid'] = True
return salt_result
def create(path, docker_compose):
'''
Create and validate a docker-compose file into a directory
path
Path where the docker-compose file will be stored on the server
docker_compose
docker_compose file
CLI Example:
.. code-block:: bash
salt myminion dockercompose.create /path/where/docker-compose/stored content
'''
if docker_compose:
ret = __write_docker_compose(path,
docker_compose,
already_existed=False)
if isinstance(ret, dict):
return ret
else:
return __standardize_result(False,
'Creating a docker-compose project failed, you must send a valid docker-compose file',
None, None)
return __standardize_result(True,
'Successfully created the docker-compose file',
{'compose.base_dir': path},
None)
def pull(path, service_names=None):
'''
Pull image for containers in the docker-compose file, service_names is a
python list, if omitted pull all images
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pull /path/where/docker-compose/stored
salt myminion dockercompose.pull /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.pull(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pulling containers images via docker-compose succeeded',
None, None)
def build(path, service_names=None):
'''
Build image for containers in the docker-compose file, service_names is a
python list, if omitted build images for all containers. Please note
that at the moment the module does not allow you to upload your Dockerfile,
nor any other file you could need with your docker-compose.yml, you will
have to make sure the files you need are actually in the directory specified
in the `build` keyword
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.build /path/where/docker-compose/stored
salt myminion dockercompose.build /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.build(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Building containers images via docker-compose succeeded',
None, None)
def restart(path, service_names=None):
'''
Restart container(s) in the docker-compose file, service_names is a python
list, if omitted restart all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will restart only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.restart /path/where/docker-compose/stored
salt myminion dockercompose.restart /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.restart(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'restarted'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Restarting containers via docker-compose', result, debug_ret)
def stop(path, service_names=None):
'''
Stop running containers in the docker-compose file, service_names is a python
list, if omitted stop all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will stop only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.stop /path/where/docker-compose/stored
salt myminion dockercompose.stop /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
def pause(path, service_names=None):
'''
Pause running containers in the docker-compose file, service_names is a python
list, if omitted pause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.pause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'paused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pausing containers via docker-compose', result, debug_ret)
def unpause(path, service_names=None):
'''
Un-Pause containers in the docker-compose file, service_names is a python
list, if omitted unpause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will un-pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.unpause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'unpaused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Un-Pausing containers via docker-compose', result, debug_ret)
def start(path, service_names=None):
'''
Start containers in the docker-compose file, service_names is a python
list, if omitted start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.start /path/where/docker-compose/stored
salt myminion dockercompose.start /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.start(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'started'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Starting containers via docker-compose', result, debug_ret)
def kill(path, service_names=None):
'''
Kill containers in the docker-compose file, service_names is a python
list, if omitted kill all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will kill only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.kill /path/where/docker-compose/stored
salt myminion dockercompose.kill /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.kill(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'killed'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Killing containers via docker-compose', result, debug_ret)
def rm(path, service_names=None):
'''
Remove stopped containers in the docker-compose file, service_names is a python
list, if omitted remove all stopped containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will remove only the specified stopped services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.rm /path/where/docker-compose/stored
salt myminion dockercompose.rm /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.remove_stopped(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Removing stopped containers via docker-compose', None, None)
def ps(path):
'''
List all running containers and report some information about them
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.ps /path/where/docker-compose/stored
'''
project = __load_project(path)
result = {}
if isinstance(project, dict):
return project
else:
if USE_FILTERCLASS:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, OneOffFilter.only),
key=attrgetter('name'))
else:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, one_off=True),
key=attrgetter('name'))
for container in containers:
command = container.human_readable_command
if len(command) > 30:
command = '{0} ...'.format(command[:26])
result[container.name] = {
'id': container.id,
'name': container.name,
'command': command,
'state': container.human_readable_state,
'ports': container.human_readable_ports,
}
return __standardize_result(True, 'Listing docker-compose containers', result, None)
def up(path, service_names=None):
'''
Create and start containers defined in the docker-compose.yml file
located in path, service_names is a python list, if omitted create and
start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will create and start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.up /path/where/docker-compose/stored
salt myminion dockercompose.up /path/where/docker-compose/stored '[janus]'
'''
debug_ret = {}
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
result = _get_convergence_plans(project, service_names)
ret = project.up(service_names)
if debug:
for container in ret:
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Adding containers via docker-compose', result, debug_ret)
def service_create(path, service_name, definition):
'''
Create the definition of a docker-compose service
This fails when the service already exists
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service {0} created'.format(service_name),
already_existed=True)
def service_upsert(path, service_name, definition):
'''
Create or update the definition of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_upsert /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service definition for {0} is set'.format(service_name),
already_existed=True)
def service_remove(path, service_name):
'''
Remove the definition of a docker-compose service
This does not rm the container
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_remove /path/where/docker-compose/stored service_name
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
del services[service_name]
return __dump_compose_file(path, compose_result,
'Service {0} is removed from {1}'.format(service_name, path),
already_existed=True)
def service_set_tag(path, service_name, tag):
'''
Change the tag of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
tag
Name of the tag (often used as version) that the service image should have
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name tag
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
if 'image' not in services[service_name]:
return __standardize_result(False,
'Service {0} did not contain the variable "image"'.format(service_name),
None, None)
image = services[service_name]['image'].split(':')[0]
services[service_name]['image'] = '{0}:{1}'.format(image, tag)
return __dump_compose_file(path, compose_result,
'Service {0} is set to tag "{1}"'.format(service_name, tag),
already_existed=True)
|
saltstack/salt
|
salt/modules/dockercompose.py
|
__dump_compose_file
|
python
|
def __dump_compose_file(path, compose_result, success_msg, already_existed):
'''
Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return:
'''
ret = __dump_docker_compose(path,
compose_result['compose_content'],
already_existed)
if isinstance(ret, dict):
return ret
return __standardize_result(True, success_msg,
compose_result['compose_content'], None)
|
Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockercompose.py#L382-L397
|
[
"def __standardize_result(status, message, data=None, debug_msg=None):\n '''\n Standardizes all responses\n\n :param status:\n :param message:\n :param data:\n :param debug_msg:\n :return:\n '''\n result = {\n 'status': status,\n 'message': message\n }\n\n if data is not None:\n result['return'] = data\n\n if debug_msg is not None and debug:\n result['debug'] = debug_msg\n\n return result\n",
"def __dump_docker_compose(path, content, already_existed):\n '''\n Dumps\n\n :param path:\n :param content: the not-yet dumped content\n :return:\n '''\n try:\n dumped = yaml.safe_dump(content, indent=2, default_flow_style=False)\n return __write_docker_compose(path, dumped, already_existed)\n except TypeError as t_err:\n msg = 'Could not dump {0} {1}'.format(content, t_err)\n return __standardize_result(False, msg,\n None, None)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to import docker-compose via saltstack
.. versionadded:: 2016.3.0
:maintainer: Jean Praloran <jeanpralo@gmail.com>
:maturity: new
:depends: docker-compose>=1.5
:platform: all
Introduction
------------
This module allows one to deal with docker-compose file in a directory.
This is a first version only, the following commands are missing at the moment
but will be built later on if the community is interested in this module:
- run
- logs
- port
- scale
Installation Prerequisites
--------------------------
This execution module requires at least version 1.4.0 of both docker-compose_ and
Docker_. docker-compose can easily be installed using :py:func:`pip.install
<salt.modules.pip.install>`:
.. code-block:: bash
salt myminion pip.install docker-compose>=1.5.0
.. _docker-compose: https://pypi.python.org/pypi/docker-compose
.. _Docker: https://www.docker.com/
How to use this module?
-----------------------
In order to use the module if you have no docker-compose file on the server you
can issue the command create, it takes two arguments the path where the
docker-compose.yml will be stored and the content of this latter:
.. code-block:: text
# salt-call -l debug dockercompose.create /tmp/toto '
database:
image: mongo:3.0
command: mongod --smallfiles --quiet --logpath=/dev/null
'
Then you can execute a list of method defined at the bottom with at least one
argument (the path where the docker-compose.yml will be read) and an optional
python list which corresponds to the services names:
.. code-block:: bash
# salt-call -l debug dockercompose.up /tmp/toto
# salt-call -l debug dockercompose.restart /tmp/toto '[database]'
# salt-call -l debug dockercompose.stop /tmp/toto
# salt-call -l debug dockercompose.rm /tmp/toto
Docker-compose method supported
-------------------------------
- up
- restart
- stop
- start
- pause
- unpause
- kill
- rm
- ps
- pull
- build
Functions
---------
- docker-compose.yml management
- :py:func:`dockercompose.create <salt.modules.dockercompose.create>`
- :py:func:`dockercompose.get <salt.modules.dockercompose.get>`
- Manage containers
- :py:func:`dockercompose.restart <salt.modules.dockercompose.restart>`
- :py:func:`dockercompose.stop <salt.modules.dockercompose.stop>`
- :py:func:`dockercompose.pause <salt.modules.dockercompose.pause>`
- :py:func:`dockercompose.unpause <salt.modules.dockercompose.unpause>`
- :py:func:`dockercompose.start <salt.modules.dockercompose.start>`
- :py:func:`dockercompose.kill <salt.modules.dockercompose.kill>`
- :py:func:`dockercompose.rm <salt.modules.dockercompose.rm>`
- :py:func:`dockercompose.up <salt.modules.dockercompose.up>`
- Manage containers image:
- :py:func:`dockercompose.pull <salt.modules.dockercompose.pull>`
- :py:func:`dockercompose.build <salt.modules.dockercompose.build>`
- Gather information about containers:
- :py:func:`dockercompose.ps <salt.modules.dockercompose.ps>`
- Manage service definitions:
- :py:func:`dockercompose.service_create <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_upsert <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_remove <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_set_tag <salt.modules.dockercompose.ps>`
Detailed Function Documentation
-------------------------------
'''
from __future__ import absolute_import, print_function, unicode_literals
import inspect
import logging
import os
import re
import salt.utils.files
import salt.utils.stringutils
from salt.ext import six
from operator import attrgetter
from salt.serializers import json
from salt.utils import yaml
try:
import compose
from compose.cli.command import get_project
from compose.service import ConvergenceStrategy
HAS_DOCKERCOMPOSE = True
except ImportError:
HAS_DOCKERCOMPOSE = False
try:
from compose.project import OneOffFilter
USE_FILTERCLASS = True
except ImportError:
USE_FILTERCLASS = False
MIN_DOCKERCOMPOSE = (1, 5, 0)
VERSION_RE = r'([\d.]+)'
log = logging.getLogger(__name__)
debug = False
__virtualname__ = 'dockercompose'
DEFAULT_DC_FILENAMES = ('docker-compose.yml', 'docker-compose.yaml')
def __virtual__():
if HAS_DOCKERCOMPOSE:
match = re.match(VERSION_RE, six.text_type(compose.__version__))
if match:
version = tuple([int(x) for x in match.group(1).split('.')])
if version >= MIN_DOCKERCOMPOSE:
return __virtualname__
return (False, 'The dockercompose execution module not loaded: '
'compose python library not available.')
def __standardize_result(status, message, data=None, debug_msg=None):
'''
Standardizes all responses
:param status:
:param message:
:param data:
:param debug_msg:
:return:
'''
result = {
'status': status,
'message': message
}
if data is not None:
result['return'] = data
if debug_msg is not None and debug:
result['debug'] = debug_msg
return result
def __get_docker_file_path(path):
'''
Determines the filepath to use
:param path:
:return:
'''
if os.path.isfile(path):
return path
for dc_filename in DEFAULT_DC_FILENAMES:
file_path = os.path.join(path, dc_filename)
if os.path.isfile(file_path):
return file_path
# implicitly return None
def __read_docker_compose_file(file_path):
'''
Read the compose file if it exists in the directory
:param file_path:
:return:
'''
if not os.path.isfile(file_path):
return __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
file_name = os.path.basename(file_path)
result = {file_name: ''}
for line in fl:
result[file_name] += salt.utils.stringutils.to_unicode(line)
except EnvironmentError:
return __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
return __standardize_result(True,
'Reading content of {0}'.format(file_path),
result, None)
def __load_docker_compose(path):
'''
Read the compose file and load its' contents
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return None, __standardize_result(False, msg,
None, None)
if not os.path.isfile(file_path):
return None, __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
loaded = yaml.load(fl)
except EnvironmentError:
return None, __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(file_path, yerr)
return None, __standardize_result(False, msg,
None, None)
if not loaded:
msg = 'Got empty compose file at {0}'.format(file_path)
return None, __standardize_result(False, msg,
None, None)
if 'services' not in loaded:
loaded['services'] = {}
result = {
'compose_content': loaded,
'file_name': os.path.basename(file_path)
}
return result, None
def __dump_docker_compose(path, content, already_existed):
'''
Dumps
:param path:
:param content: the not-yet dumped content
:return:
'''
try:
dumped = yaml.safe_dump(content, indent=2, default_flow_style=False)
return __write_docker_compose(path, dumped, already_existed)
except TypeError as t_err:
msg = 'Could not dump {0} {1}'.format(content, t_err)
return __standardize_result(False, msg,
None, None)
def __write_docker_compose(path, docker_compose, already_existed):
'''
Write docker-compose to a path
in order to use it with docker-compose ( config check )
:param path:
docker_compose
contains the docker-compose file
:return:
'''
if path.lower().endswith(('.yml', '.yaml')):
file_path = path
dir_name = os.path.dirname(path)
else:
dir_name = path
file_path = os.path.join(dir_name, DEFAULT_DC_FILENAMES[0])
if os.path.isdir(dir_name) is False:
os.mkdir(dir_name)
try:
with salt.utils.files.fopen(file_path, 'w') as fl:
fl.write(salt.utils.stringutils.to_str(docker_compose))
except EnvironmentError:
return __standardize_result(False,
'Could not write {0}'.format(file_path),
None, None)
project = __load_project_from_file_path(file_path)
if isinstance(project, dict):
if not already_existed:
os.remove(file_path)
return project
return file_path
def __load_project(path):
'''
Load a docker-compose project from path
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return __standardize_result(False,
msg,
None, None)
return __load_project_from_file_path(file_path)
def __load_project_from_file_path(file_path):
'''
Load a docker-compose project from file path
:param path:
:return:
'''
try:
project = get_project(project_dir=os.path.dirname(file_path),
config_path=[os.path.basename(file_path)])
except Exception as inst:
return __handle_except(inst)
return project
def __load_compose_definitions(path, definition):
'''
Will load the compose file located at path
Then determines the format/contents of the sent definition
err or results are only set if there were any
:param path:
:param definition:
:return tuple(compose_result, loaded_definition, err):
'''
compose_result, err = __load_docker_compose(path)
if err:
return None, None, err
if isinstance(definition, dict):
return compose_result, definition, None
elif definition.strip().startswith('{'):
try:
loaded_definition = json.deserialize(definition)
except json.DeserializationError as jerr:
msg = 'Could not parse {0} {1}'.format(definition, jerr)
return None, None, __standardize_result(False, msg,
None, None)
else:
try:
loaded_definition = yaml.load(definition)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(definition, yerr)
return None, None, __standardize_result(False, msg,
None, None)
return compose_result, loaded_definition, None
def __handle_except(inst):
'''
Handle exception and return a standard result
:param inst:
:return:
'''
return __standardize_result(False,
'Docker-compose command {0} failed'.
format(inspect.stack()[1][3]),
'{0}'.format(inst), None)
def _get_convergence_plans(project, service_names):
'''
Get action executed for each container
:param project:
:param service_names:
:return:
'''
ret = {}
plans = project._get_convergence_plans(project.get_services(service_names),
ConvergenceStrategy.changed)
for cont in plans:
(action, container) = plans[cont]
if action == 'create':
ret[cont] = 'Creating container'
elif action == 'recreate':
ret[cont] = 'Re-creating container'
elif action == 'start':
ret[cont] = 'Starting container'
elif action == 'noop':
ret[cont] = 'Container is up to date'
return ret
def get(path):
'''
Get the content of the docker-compose file into a directory
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.get /path/where/docker-compose/stored
'''
file_path = __get_docker_file_path(path)
if file_path is None:
return __standardize_result(False,
'Path {} is not present'.format(path),
None, None)
salt_result = __read_docker_compose_file(file_path)
if not salt_result['status']:
return salt_result
project = __load_project(path)
if isinstance(project, dict):
salt_result['return']['valid'] = False
else:
salt_result['return']['valid'] = True
return salt_result
def create(path, docker_compose):
'''
Create and validate a docker-compose file into a directory
path
Path where the docker-compose file will be stored on the server
docker_compose
docker_compose file
CLI Example:
.. code-block:: bash
salt myminion dockercompose.create /path/where/docker-compose/stored content
'''
if docker_compose:
ret = __write_docker_compose(path,
docker_compose,
already_existed=False)
if isinstance(ret, dict):
return ret
else:
return __standardize_result(False,
'Creating a docker-compose project failed, you must send a valid docker-compose file',
None, None)
return __standardize_result(True,
'Successfully created the docker-compose file',
{'compose.base_dir': path},
None)
def pull(path, service_names=None):
'''
Pull image for containers in the docker-compose file, service_names is a
python list, if omitted pull all images
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pull /path/where/docker-compose/stored
salt myminion dockercompose.pull /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.pull(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pulling containers images via docker-compose succeeded',
None, None)
def build(path, service_names=None):
'''
Build image for containers in the docker-compose file, service_names is a
python list, if omitted build images for all containers. Please note
that at the moment the module does not allow you to upload your Dockerfile,
nor any other file you could need with your docker-compose.yml, you will
have to make sure the files you need are actually in the directory specified
in the `build` keyword
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.build /path/where/docker-compose/stored
salt myminion dockercompose.build /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.build(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Building containers images via docker-compose succeeded',
None, None)
def restart(path, service_names=None):
'''
Restart container(s) in the docker-compose file, service_names is a python
list, if omitted restart all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will restart only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.restart /path/where/docker-compose/stored
salt myminion dockercompose.restart /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.restart(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'restarted'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Restarting containers via docker-compose', result, debug_ret)
def stop(path, service_names=None):
'''
Stop running containers in the docker-compose file, service_names is a python
list, if omitted stop all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will stop only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.stop /path/where/docker-compose/stored
salt myminion dockercompose.stop /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
def pause(path, service_names=None):
'''
Pause running containers in the docker-compose file, service_names is a python
list, if omitted pause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.pause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'paused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pausing containers via docker-compose', result, debug_ret)
def unpause(path, service_names=None):
'''
Un-Pause containers in the docker-compose file, service_names is a python
list, if omitted unpause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will un-pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.unpause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'unpaused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Un-Pausing containers via docker-compose', result, debug_ret)
def start(path, service_names=None):
'''
Start containers in the docker-compose file, service_names is a python
list, if omitted start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.start /path/where/docker-compose/stored
salt myminion dockercompose.start /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.start(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'started'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Starting containers via docker-compose', result, debug_ret)
def kill(path, service_names=None):
'''
Kill containers in the docker-compose file, service_names is a python
list, if omitted kill all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will kill only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.kill /path/where/docker-compose/stored
salt myminion dockercompose.kill /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.kill(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'killed'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Killing containers via docker-compose', result, debug_ret)
def rm(path, service_names=None):
'''
Remove stopped containers in the docker-compose file, service_names is a python
list, if omitted remove all stopped containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will remove only the specified stopped services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.rm /path/where/docker-compose/stored
salt myminion dockercompose.rm /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.remove_stopped(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Removing stopped containers via docker-compose', None, None)
def ps(path):
'''
List all running containers and report some information about them
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.ps /path/where/docker-compose/stored
'''
project = __load_project(path)
result = {}
if isinstance(project, dict):
return project
else:
if USE_FILTERCLASS:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, OneOffFilter.only),
key=attrgetter('name'))
else:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, one_off=True),
key=attrgetter('name'))
for container in containers:
command = container.human_readable_command
if len(command) > 30:
command = '{0} ...'.format(command[:26])
result[container.name] = {
'id': container.id,
'name': container.name,
'command': command,
'state': container.human_readable_state,
'ports': container.human_readable_ports,
}
return __standardize_result(True, 'Listing docker-compose containers', result, None)
def up(path, service_names=None):
'''
Create and start containers defined in the docker-compose.yml file
located in path, service_names is a python list, if omitted create and
start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will create and start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.up /path/where/docker-compose/stored
salt myminion dockercompose.up /path/where/docker-compose/stored '[janus]'
'''
debug_ret = {}
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
result = _get_convergence_plans(project, service_names)
ret = project.up(service_names)
if debug:
for container in ret:
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Adding containers via docker-compose', result, debug_ret)
def service_create(path, service_name, definition):
'''
Create the definition of a docker-compose service
This fails when the service already exists
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service {0} created'.format(service_name),
already_existed=True)
def service_upsert(path, service_name, definition):
'''
Create or update the definition of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_upsert /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service definition for {0} is set'.format(service_name),
already_existed=True)
def service_remove(path, service_name):
'''
Remove the definition of a docker-compose service
This does not rm the container
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_remove /path/where/docker-compose/stored service_name
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
del services[service_name]
return __dump_compose_file(path, compose_result,
'Service {0} is removed from {1}'.format(service_name, path),
already_existed=True)
def service_set_tag(path, service_name, tag):
'''
Change the tag of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
tag
Name of the tag (often used as version) that the service image should have
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name tag
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
if 'image' not in services[service_name]:
return __standardize_result(False,
'Service {0} did not contain the variable "image"'.format(service_name),
None, None)
image = services[service_name]['image'].split(':')[0]
services[service_name]['image'] = '{0}:{1}'.format(image, tag)
return __dump_compose_file(path, compose_result,
'Service {0} is set to tag "{1}"'.format(service_name, tag),
already_existed=True)
|
saltstack/salt
|
salt/modules/dockercompose.py
|
_get_convergence_plans
|
python
|
def _get_convergence_plans(project, service_names):
'''
Get action executed for each container
:param project:
:param service_names:
:return:
'''
ret = {}
plans = project._get_convergence_plans(project.get_services(service_names),
ConvergenceStrategy.changed)
for cont in plans:
(action, container) = plans[cont]
if action == 'create':
ret[cont] = 'Creating container'
elif action == 'recreate':
ret[cont] = 'Re-creating container'
elif action == 'start':
ret[cont] = 'Starting container'
elif action == 'noop':
ret[cont] = 'Container is up to date'
return ret
|
Get action executed for each container
:param project:
:param service_names:
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockercompose.py#L413-L434
| null |
# -*- coding: utf-8 -*-
'''
Module to import docker-compose via saltstack
.. versionadded:: 2016.3.0
:maintainer: Jean Praloran <jeanpralo@gmail.com>
:maturity: new
:depends: docker-compose>=1.5
:platform: all
Introduction
------------
This module allows one to deal with docker-compose file in a directory.
This is a first version only, the following commands are missing at the moment
but will be built later on if the community is interested in this module:
- run
- logs
- port
- scale
Installation Prerequisites
--------------------------
This execution module requires at least version 1.4.0 of both docker-compose_ and
Docker_. docker-compose can easily be installed using :py:func:`pip.install
<salt.modules.pip.install>`:
.. code-block:: bash
salt myminion pip.install docker-compose>=1.5.0
.. _docker-compose: https://pypi.python.org/pypi/docker-compose
.. _Docker: https://www.docker.com/
How to use this module?
-----------------------
In order to use the module if you have no docker-compose file on the server you
can issue the command create, it takes two arguments the path where the
docker-compose.yml will be stored and the content of this latter:
.. code-block:: text
# salt-call -l debug dockercompose.create /tmp/toto '
database:
image: mongo:3.0
command: mongod --smallfiles --quiet --logpath=/dev/null
'
Then you can execute a list of method defined at the bottom with at least one
argument (the path where the docker-compose.yml will be read) and an optional
python list which corresponds to the services names:
.. code-block:: bash
# salt-call -l debug dockercompose.up /tmp/toto
# salt-call -l debug dockercompose.restart /tmp/toto '[database]'
# salt-call -l debug dockercompose.stop /tmp/toto
# salt-call -l debug dockercompose.rm /tmp/toto
Docker-compose method supported
-------------------------------
- up
- restart
- stop
- start
- pause
- unpause
- kill
- rm
- ps
- pull
- build
Functions
---------
- docker-compose.yml management
- :py:func:`dockercompose.create <salt.modules.dockercompose.create>`
- :py:func:`dockercompose.get <salt.modules.dockercompose.get>`
- Manage containers
- :py:func:`dockercompose.restart <salt.modules.dockercompose.restart>`
- :py:func:`dockercompose.stop <salt.modules.dockercompose.stop>`
- :py:func:`dockercompose.pause <salt.modules.dockercompose.pause>`
- :py:func:`dockercompose.unpause <salt.modules.dockercompose.unpause>`
- :py:func:`dockercompose.start <salt.modules.dockercompose.start>`
- :py:func:`dockercompose.kill <salt.modules.dockercompose.kill>`
- :py:func:`dockercompose.rm <salt.modules.dockercompose.rm>`
- :py:func:`dockercompose.up <salt.modules.dockercompose.up>`
- Manage containers image:
- :py:func:`dockercompose.pull <salt.modules.dockercompose.pull>`
- :py:func:`dockercompose.build <salt.modules.dockercompose.build>`
- Gather information about containers:
- :py:func:`dockercompose.ps <salt.modules.dockercompose.ps>`
- Manage service definitions:
- :py:func:`dockercompose.service_create <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_upsert <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_remove <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_set_tag <salt.modules.dockercompose.ps>`
Detailed Function Documentation
-------------------------------
'''
from __future__ import absolute_import, print_function, unicode_literals
import inspect
import logging
import os
import re
import salt.utils.files
import salt.utils.stringutils
from salt.ext import six
from operator import attrgetter
from salt.serializers import json
from salt.utils import yaml
try:
import compose
from compose.cli.command import get_project
from compose.service import ConvergenceStrategy
HAS_DOCKERCOMPOSE = True
except ImportError:
HAS_DOCKERCOMPOSE = False
try:
from compose.project import OneOffFilter
USE_FILTERCLASS = True
except ImportError:
USE_FILTERCLASS = False
MIN_DOCKERCOMPOSE = (1, 5, 0)
VERSION_RE = r'([\d.]+)'
log = logging.getLogger(__name__)
debug = False
__virtualname__ = 'dockercompose'
DEFAULT_DC_FILENAMES = ('docker-compose.yml', 'docker-compose.yaml')
def __virtual__():
if HAS_DOCKERCOMPOSE:
match = re.match(VERSION_RE, six.text_type(compose.__version__))
if match:
version = tuple([int(x) for x in match.group(1).split('.')])
if version >= MIN_DOCKERCOMPOSE:
return __virtualname__
return (False, 'The dockercompose execution module not loaded: '
'compose python library not available.')
def __standardize_result(status, message, data=None, debug_msg=None):
'''
Standardizes all responses
:param status:
:param message:
:param data:
:param debug_msg:
:return:
'''
result = {
'status': status,
'message': message
}
if data is not None:
result['return'] = data
if debug_msg is not None and debug:
result['debug'] = debug_msg
return result
def __get_docker_file_path(path):
'''
Determines the filepath to use
:param path:
:return:
'''
if os.path.isfile(path):
return path
for dc_filename in DEFAULT_DC_FILENAMES:
file_path = os.path.join(path, dc_filename)
if os.path.isfile(file_path):
return file_path
# implicitly return None
def __read_docker_compose_file(file_path):
'''
Read the compose file if it exists in the directory
:param file_path:
:return:
'''
if not os.path.isfile(file_path):
return __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
file_name = os.path.basename(file_path)
result = {file_name: ''}
for line in fl:
result[file_name] += salt.utils.stringutils.to_unicode(line)
except EnvironmentError:
return __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
return __standardize_result(True,
'Reading content of {0}'.format(file_path),
result, None)
def __load_docker_compose(path):
'''
Read the compose file and load its' contents
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return None, __standardize_result(False, msg,
None, None)
if not os.path.isfile(file_path):
return None, __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
loaded = yaml.load(fl)
except EnvironmentError:
return None, __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(file_path, yerr)
return None, __standardize_result(False, msg,
None, None)
if not loaded:
msg = 'Got empty compose file at {0}'.format(file_path)
return None, __standardize_result(False, msg,
None, None)
if 'services' not in loaded:
loaded['services'] = {}
result = {
'compose_content': loaded,
'file_name': os.path.basename(file_path)
}
return result, None
def __dump_docker_compose(path, content, already_existed):
'''
Dumps
:param path:
:param content: the not-yet dumped content
:return:
'''
try:
dumped = yaml.safe_dump(content, indent=2, default_flow_style=False)
return __write_docker_compose(path, dumped, already_existed)
except TypeError as t_err:
msg = 'Could not dump {0} {1}'.format(content, t_err)
return __standardize_result(False, msg,
None, None)
def __write_docker_compose(path, docker_compose, already_existed):
'''
Write docker-compose to a path
in order to use it with docker-compose ( config check )
:param path:
docker_compose
contains the docker-compose file
:return:
'''
if path.lower().endswith(('.yml', '.yaml')):
file_path = path
dir_name = os.path.dirname(path)
else:
dir_name = path
file_path = os.path.join(dir_name, DEFAULT_DC_FILENAMES[0])
if os.path.isdir(dir_name) is False:
os.mkdir(dir_name)
try:
with salt.utils.files.fopen(file_path, 'w') as fl:
fl.write(salt.utils.stringutils.to_str(docker_compose))
except EnvironmentError:
return __standardize_result(False,
'Could not write {0}'.format(file_path),
None, None)
project = __load_project_from_file_path(file_path)
if isinstance(project, dict):
if not already_existed:
os.remove(file_path)
return project
return file_path
def __load_project(path):
'''
Load a docker-compose project from path
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return __standardize_result(False,
msg,
None, None)
return __load_project_from_file_path(file_path)
def __load_project_from_file_path(file_path):
'''
Load a docker-compose project from file path
:param path:
:return:
'''
try:
project = get_project(project_dir=os.path.dirname(file_path),
config_path=[os.path.basename(file_path)])
except Exception as inst:
return __handle_except(inst)
return project
def __load_compose_definitions(path, definition):
'''
Will load the compose file located at path
Then determines the format/contents of the sent definition
err or results are only set if there were any
:param path:
:param definition:
:return tuple(compose_result, loaded_definition, err):
'''
compose_result, err = __load_docker_compose(path)
if err:
return None, None, err
if isinstance(definition, dict):
return compose_result, definition, None
elif definition.strip().startswith('{'):
try:
loaded_definition = json.deserialize(definition)
except json.DeserializationError as jerr:
msg = 'Could not parse {0} {1}'.format(definition, jerr)
return None, None, __standardize_result(False, msg,
None, None)
else:
try:
loaded_definition = yaml.load(definition)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(definition, yerr)
return None, None, __standardize_result(False, msg,
None, None)
return compose_result, loaded_definition, None
def __dump_compose_file(path, compose_result, success_msg, already_existed):
'''
Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return:
'''
ret = __dump_docker_compose(path,
compose_result['compose_content'],
already_existed)
if isinstance(ret, dict):
return ret
return __standardize_result(True, success_msg,
compose_result['compose_content'], None)
def __handle_except(inst):
'''
Handle exception and return a standard result
:param inst:
:return:
'''
return __standardize_result(False,
'Docker-compose command {0} failed'.
format(inspect.stack()[1][3]),
'{0}'.format(inst), None)
def get(path):
'''
Get the content of the docker-compose file into a directory
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.get /path/where/docker-compose/stored
'''
file_path = __get_docker_file_path(path)
if file_path is None:
return __standardize_result(False,
'Path {} is not present'.format(path),
None, None)
salt_result = __read_docker_compose_file(file_path)
if not salt_result['status']:
return salt_result
project = __load_project(path)
if isinstance(project, dict):
salt_result['return']['valid'] = False
else:
salt_result['return']['valid'] = True
return salt_result
def create(path, docker_compose):
'''
Create and validate a docker-compose file into a directory
path
Path where the docker-compose file will be stored on the server
docker_compose
docker_compose file
CLI Example:
.. code-block:: bash
salt myminion dockercompose.create /path/where/docker-compose/stored content
'''
if docker_compose:
ret = __write_docker_compose(path,
docker_compose,
already_existed=False)
if isinstance(ret, dict):
return ret
else:
return __standardize_result(False,
'Creating a docker-compose project failed, you must send a valid docker-compose file',
None, None)
return __standardize_result(True,
'Successfully created the docker-compose file',
{'compose.base_dir': path},
None)
def pull(path, service_names=None):
'''
Pull image for containers in the docker-compose file, service_names is a
python list, if omitted pull all images
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pull /path/where/docker-compose/stored
salt myminion dockercompose.pull /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.pull(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pulling containers images via docker-compose succeeded',
None, None)
def build(path, service_names=None):
'''
Build image for containers in the docker-compose file, service_names is a
python list, if omitted build images for all containers. Please note
that at the moment the module does not allow you to upload your Dockerfile,
nor any other file you could need with your docker-compose.yml, you will
have to make sure the files you need are actually in the directory specified
in the `build` keyword
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.build /path/where/docker-compose/stored
salt myminion dockercompose.build /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.build(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Building containers images via docker-compose succeeded',
None, None)
def restart(path, service_names=None):
'''
Restart container(s) in the docker-compose file, service_names is a python
list, if omitted restart all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will restart only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.restart /path/where/docker-compose/stored
salt myminion dockercompose.restart /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.restart(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'restarted'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Restarting containers via docker-compose', result, debug_ret)
def stop(path, service_names=None):
'''
Stop running containers in the docker-compose file, service_names is a python
list, if omitted stop all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will stop only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.stop /path/where/docker-compose/stored
salt myminion dockercompose.stop /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
def pause(path, service_names=None):
'''
Pause running containers in the docker-compose file, service_names is a python
list, if omitted pause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.pause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'paused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pausing containers via docker-compose', result, debug_ret)
def unpause(path, service_names=None):
'''
Un-Pause containers in the docker-compose file, service_names is a python
list, if omitted unpause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will un-pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.unpause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'unpaused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Un-Pausing containers via docker-compose', result, debug_ret)
def start(path, service_names=None):
'''
Start containers in the docker-compose file, service_names is a python
list, if omitted start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.start /path/where/docker-compose/stored
salt myminion dockercompose.start /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.start(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'started'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Starting containers via docker-compose', result, debug_ret)
def kill(path, service_names=None):
'''
Kill containers in the docker-compose file, service_names is a python
list, if omitted kill all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will kill only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.kill /path/where/docker-compose/stored
salt myminion dockercompose.kill /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.kill(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'killed'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Killing containers via docker-compose', result, debug_ret)
def rm(path, service_names=None):
'''
Remove stopped containers in the docker-compose file, service_names is a python
list, if omitted remove all stopped containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will remove only the specified stopped services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.rm /path/where/docker-compose/stored
salt myminion dockercompose.rm /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.remove_stopped(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Removing stopped containers via docker-compose', None, None)
def ps(path):
'''
List all running containers and report some information about them
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.ps /path/where/docker-compose/stored
'''
project = __load_project(path)
result = {}
if isinstance(project, dict):
return project
else:
if USE_FILTERCLASS:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, OneOffFilter.only),
key=attrgetter('name'))
else:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, one_off=True),
key=attrgetter('name'))
for container in containers:
command = container.human_readable_command
if len(command) > 30:
command = '{0} ...'.format(command[:26])
result[container.name] = {
'id': container.id,
'name': container.name,
'command': command,
'state': container.human_readable_state,
'ports': container.human_readable_ports,
}
return __standardize_result(True, 'Listing docker-compose containers', result, None)
def up(path, service_names=None):
'''
Create and start containers defined in the docker-compose.yml file
located in path, service_names is a python list, if omitted create and
start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will create and start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.up /path/where/docker-compose/stored
salt myminion dockercompose.up /path/where/docker-compose/stored '[janus]'
'''
debug_ret = {}
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
result = _get_convergence_plans(project, service_names)
ret = project.up(service_names)
if debug:
for container in ret:
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Adding containers via docker-compose', result, debug_ret)
def service_create(path, service_name, definition):
'''
Create the definition of a docker-compose service
This fails when the service already exists
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service {0} created'.format(service_name),
already_existed=True)
def service_upsert(path, service_name, definition):
'''
Create or update the definition of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_upsert /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service definition for {0} is set'.format(service_name),
already_existed=True)
def service_remove(path, service_name):
'''
Remove the definition of a docker-compose service
This does not rm the container
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_remove /path/where/docker-compose/stored service_name
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
del services[service_name]
return __dump_compose_file(path, compose_result,
'Service {0} is removed from {1}'.format(service_name, path),
already_existed=True)
def service_set_tag(path, service_name, tag):
'''
Change the tag of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
tag
Name of the tag (often used as version) that the service image should have
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name tag
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
if 'image' not in services[service_name]:
return __standardize_result(False,
'Service {0} did not contain the variable "image"'.format(service_name),
None, None)
image = services[service_name]['image'].split(':')[0]
services[service_name]['image'] = '{0}:{1}'.format(image, tag)
return __dump_compose_file(path, compose_result,
'Service {0} is set to tag "{1}"'.format(service_name, tag),
already_existed=True)
|
saltstack/salt
|
salt/modules/dockercompose.py
|
get
|
python
|
def get(path):
'''
Get the content of the docker-compose file into a directory
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.get /path/where/docker-compose/stored
'''
file_path = __get_docker_file_path(path)
if file_path is None:
return __standardize_result(False,
'Path {} is not present'.format(path),
None, None)
salt_result = __read_docker_compose_file(file_path)
if not salt_result['status']:
return salt_result
project = __load_project(path)
if isinstance(project, dict):
salt_result['return']['valid'] = False
else:
salt_result['return']['valid'] = True
return salt_result
|
Get the content of the docker-compose file into a directory
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.get /path/where/docker-compose/stored
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockercompose.py#L437-L463
|
[
"def __standardize_result(status, message, data=None, debug_msg=None):\n '''\n Standardizes all responses\n\n :param status:\n :param message:\n :param data:\n :param debug_msg:\n :return:\n '''\n result = {\n 'status': status,\n 'message': message\n }\n\n if data is not None:\n result['return'] = data\n\n if debug_msg is not None and debug:\n result['debug'] = debug_msg\n\n return result\n",
"def __get_docker_file_path(path):\n '''\n Determines the filepath to use\n\n :param path:\n :return:\n '''\n if os.path.isfile(path):\n return path\n for dc_filename in DEFAULT_DC_FILENAMES:\n file_path = os.path.join(path, dc_filename)\n if os.path.isfile(file_path):\n return file_path\n",
"def __read_docker_compose_file(file_path):\n '''\n Read the compose file if it exists in the directory\n\n :param file_path:\n :return:\n '''\n if not os.path.isfile(file_path):\n return __standardize_result(False,\n 'Path {} is not present'.format(file_path),\n None, None)\n try:\n with salt.utils.files.fopen(file_path, 'r') as fl:\n file_name = os.path.basename(file_path)\n result = {file_name: ''}\n for line in fl:\n result[file_name] += salt.utils.stringutils.to_unicode(line)\n except EnvironmentError:\n return __standardize_result(False,\n 'Could not read {0}'.format(file_path),\n None, None)\n return __standardize_result(True,\n 'Reading content of {0}'.format(file_path),\n result, None)\n",
"def __load_project(path):\n '''\n Load a docker-compose project from path\n\n :param path:\n :return:\n '''\n file_path = __get_docker_file_path(path)\n if file_path is None:\n msg = 'Could not find docker-compose file at {0}'.format(path)\n return __standardize_result(False,\n msg,\n None, None)\n return __load_project_from_file_path(file_path)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to import docker-compose via saltstack
.. versionadded:: 2016.3.0
:maintainer: Jean Praloran <jeanpralo@gmail.com>
:maturity: new
:depends: docker-compose>=1.5
:platform: all
Introduction
------------
This module allows one to deal with docker-compose file in a directory.
This is a first version only, the following commands are missing at the moment
but will be built later on if the community is interested in this module:
- run
- logs
- port
- scale
Installation Prerequisites
--------------------------
This execution module requires at least version 1.4.0 of both docker-compose_ and
Docker_. docker-compose can easily be installed using :py:func:`pip.install
<salt.modules.pip.install>`:
.. code-block:: bash
salt myminion pip.install docker-compose>=1.5.0
.. _docker-compose: https://pypi.python.org/pypi/docker-compose
.. _Docker: https://www.docker.com/
How to use this module?
-----------------------
In order to use the module if you have no docker-compose file on the server you
can issue the command create, it takes two arguments the path where the
docker-compose.yml will be stored and the content of this latter:
.. code-block:: text
# salt-call -l debug dockercompose.create /tmp/toto '
database:
image: mongo:3.0
command: mongod --smallfiles --quiet --logpath=/dev/null
'
Then you can execute a list of method defined at the bottom with at least one
argument (the path where the docker-compose.yml will be read) and an optional
python list which corresponds to the services names:
.. code-block:: bash
# salt-call -l debug dockercompose.up /tmp/toto
# salt-call -l debug dockercompose.restart /tmp/toto '[database]'
# salt-call -l debug dockercompose.stop /tmp/toto
# salt-call -l debug dockercompose.rm /tmp/toto
Docker-compose method supported
-------------------------------
- up
- restart
- stop
- start
- pause
- unpause
- kill
- rm
- ps
- pull
- build
Functions
---------
- docker-compose.yml management
- :py:func:`dockercompose.create <salt.modules.dockercompose.create>`
- :py:func:`dockercompose.get <salt.modules.dockercompose.get>`
- Manage containers
- :py:func:`dockercompose.restart <salt.modules.dockercompose.restart>`
- :py:func:`dockercompose.stop <salt.modules.dockercompose.stop>`
- :py:func:`dockercompose.pause <salt.modules.dockercompose.pause>`
- :py:func:`dockercompose.unpause <salt.modules.dockercompose.unpause>`
- :py:func:`dockercompose.start <salt.modules.dockercompose.start>`
- :py:func:`dockercompose.kill <salt.modules.dockercompose.kill>`
- :py:func:`dockercompose.rm <salt.modules.dockercompose.rm>`
- :py:func:`dockercompose.up <salt.modules.dockercompose.up>`
- Manage containers image:
- :py:func:`dockercompose.pull <salt.modules.dockercompose.pull>`
- :py:func:`dockercompose.build <salt.modules.dockercompose.build>`
- Gather information about containers:
- :py:func:`dockercompose.ps <salt.modules.dockercompose.ps>`
- Manage service definitions:
- :py:func:`dockercompose.service_create <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_upsert <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_remove <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_set_tag <salt.modules.dockercompose.ps>`
Detailed Function Documentation
-------------------------------
'''
from __future__ import absolute_import, print_function, unicode_literals
import inspect
import logging
import os
import re
import salt.utils.files
import salt.utils.stringutils
from salt.ext import six
from operator import attrgetter
from salt.serializers import json
from salt.utils import yaml
try:
import compose
from compose.cli.command import get_project
from compose.service import ConvergenceStrategy
HAS_DOCKERCOMPOSE = True
except ImportError:
HAS_DOCKERCOMPOSE = False
try:
from compose.project import OneOffFilter
USE_FILTERCLASS = True
except ImportError:
USE_FILTERCLASS = False
MIN_DOCKERCOMPOSE = (1, 5, 0)
VERSION_RE = r'([\d.]+)'
log = logging.getLogger(__name__)
debug = False
__virtualname__ = 'dockercompose'
DEFAULT_DC_FILENAMES = ('docker-compose.yml', 'docker-compose.yaml')
def __virtual__():
if HAS_DOCKERCOMPOSE:
match = re.match(VERSION_RE, six.text_type(compose.__version__))
if match:
version = tuple([int(x) for x in match.group(1).split('.')])
if version >= MIN_DOCKERCOMPOSE:
return __virtualname__
return (False, 'The dockercompose execution module not loaded: '
'compose python library not available.')
def __standardize_result(status, message, data=None, debug_msg=None):
'''
Standardizes all responses
:param status:
:param message:
:param data:
:param debug_msg:
:return:
'''
result = {
'status': status,
'message': message
}
if data is not None:
result['return'] = data
if debug_msg is not None and debug:
result['debug'] = debug_msg
return result
def __get_docker_file_path(path):
'''
Determines the filepath to use
:param path:
:return:
'''
if os.path.isfile(path):
return path
for dc_filename in DEFAULT_DC_FILENAMES:
file_path = os.path.join(path, dc_filename)
if os.path.isfile(file_path):
return file_path
# implicitly return None
def __read_docker_compose_file(file_path):
'''
Read the compose file if it exists in the directory
:param file_path:
:return:
'''
if not os.path.isfile(file_path):
return __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
file_name = os.path.basename(file_path)
result = {file_name: ''}
for line in fl:
result[file_name] += salt.utils.stringutils.to_unicode(line)
except EnvironmentError:
return __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
return __standardize_result(True,
'Reading content of {0}'.format(file_path),
result, None)
def __load_docker_compose(path):
'''
Read the compose file and load its' contents
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return None, __standardize_result(False, msg,
None, None)
if not os.path.isfile(file_path):
return None, __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
loaded = yaml.load(fl)
except EnvironmentError:
return None, __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(file_path, yerr)
return None, __standardize_result(False, msg,
None, None)
if not loaded:
msg = 'Got empty compose file at {0}'.format(file_path)
return None, __standardize_result(False, msg,
None, None)
if 'services' not in loaded:
loaded['services'] = {}
result = {
'compose_content': loaded,
'file_name': os.path.basename(file_path)
}
return result, None
def __dump_docker_compose(path, content, already_existed):
'''
Dumps
:param path:
:param content: the not-yet dumped content
:return:
'''
try:
dumped = yaml.safe_dump(content, indent=2, default_flow_style=False)
return __write_docker_compose(path, dumped, already_existed)
except TypeError as t_err:
msg = 'Could not dump {0} {1}'.format(content, t_err)
return __standardize_result(False, msg,
None, None)
def __write_docker_compose(path, docker_compose, already_existed):
'''
Write docker-compose to a path
in order to use it with docker-compose ( config check )
:param path:
docker_compose
contains the docker-compose file
:return:
'''
if path.lower().endswith(('.yml', '.yaml')):
file_path = path
dir_name = os.path.dirname(path)
else:
dir_name = path
file_path = os.path.join(dir_name, DEFAULT_DC_FILENAMES[0])
if os.path.isdir(dir_name) is False:
os.mkdir(dir_name)
try:
with salt.utils.files.fopen(file_path, 'w') as fl:
fl.write(salt.utils.stringutils.to_str(docker_compose))
except EnvironmentError:
return __standardize_result(False,
'Could not write {0}'.format(file_path),
None, None)
project = __load_project_from_file_path(file_path)
if isinstance(project, dict):
if not already_existed:
os.remove(file_path)
return project
return file_path
def __load_project(path):
'''
Load a docker-compose project from path
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return __standardize_result(False,
msg,
None, None)
return __load_project_from_file_path(file_path)
def __load_project_from_file_path(file_path):
'''
Load a docker-compose project from file path
:param path:
:return:
'''
try:
project = get_project(project_dir=os.path.dirname(file_path),
config_path=[os.path.basename(file_path)])
except Exception as inst:
return __handle_except(inst)
return project
def __load_compose_definitions(path, definition):
'''
Will load the compose file located at path
Then determines the format/contents of the sent definition
err or results are only set if there were any
:param path:
:param definition:
:return tuple(compose_result, loaded_definition, err):
'''
compose_result, err = __load_docker_compose(path)
if err:
return None, None, err
if isinstance(definition, dict):
return compose_result, definition, None
elif definition.strip().startswith('{'):
try:
loaded_definition = json.deserialize(definition)
except json.DeserializationError as jerr:
msg = 'Could not parse {0} {1}'.format(definition, jerr)
return None, None, __standardize_result(False, msg,
None, None)
else:
try:
loaded_definition = yaml.load(definition)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(definition, yerr)
return None, None, __standardize_result(False, msg,
None, None)
return compose_result, loaded_definition, None
def __dump_compose_file(path, compose_result, success_msg, already_existed):
'''
Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return:
'''
ret = __dump_docker_compose(path,
compose_result['compose_content'],
already_existed)
if isinstance(ret, dict):
return ret
return __standardize_result(True, success_msg,
compose_result['compose_content'], None)
def __handle_except(inst):
'''
Handle exception and return a standard result
:param inst:
:return:
'''
return __standardize_result(False,
'Docker-compose command {0} failed'.
format(inspect.stack()[1][3]),
'{0}'.format(inst), None)
def _get_convergence_plans(project, service_names):
'''
Get action executed for each container
:param project:
:param service_names:
:return:
'''
ret = {}
plans = project._get_convergence_plans(project.get_services(service_names),
ConvergenceStrategy.changed)
for cont in plans:
(action, container) = plans[cont]
if action == 'create':
ret[cont] = 'Creating container'
elif action == 'recreate':
ret[cont] = 'Re-creating container'
elif action == 'start':
ret[cont] = 'Starting container'
elif action == 'noop':
ret[cont] = 'Container is up to date'
return ret
def create(path, docker_compose):
'''
Create and validate a docker-compose file into a directory
path
Path where the docker-compose file will be stored on the server
docker_compose
docker_compose file
CLI Example:
.. code-block:: bash
salt myminion dockercompose.create /path/where/docker-compose/stored content
'''
if docker_compose:
ret = __write_docker_compose(path,
docker_compose,
already_existed=False)
if isinstance(ret, dict):
return ret
else:
return __standardize_result(False,
'Creating a docker-compose project failed, you must send a valid docker-compose file',
None, None)
return __standardize_result(True,
'Successfully created the docker-compose file',
{'compose.base_dir': path},
None)
def pull(path, service_names=None):
'''
Pull image for containers in the docker-compose file, service_names is a
python list, if omitted pull all images
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pull /path/where/docker-compose/stored
salt myminion dockercompose.pull /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.pull(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pulling containers images via docker-compose succeeded',
None, None)
def build(path, service_names=None):
'''
Build image for containers in the docker-compose file, service_names is a
python list, if omitted build images for all containers. Please note
that at the moment the module does not allow you to upload your Dockerfile,
nor any other file you could need with your docker-compose.yml, you will
have to make sure the files you need are actually in the directory specified
in the `build` keyword
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.build /path/where/docker-compose/stored
salt myminion dockercompose.build /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.build(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Building containers images via docker-compose succeeded',
None, None)
def restart(path, service_names=None):
'''
Restart container(s) in the docker-compose file, service_names is a python
list, if omitted restart all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will restart only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.restart /path/where/docker-compose/stored
salt myminion dockercompose.restart /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.restart(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'restarted'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Restarting containers via docker-compose', result, debug_ret)
def stop(path, service_names=None):
'''
Stop running containers in the docker-compose file, service_names is a python
list, if omitted stop all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will stop only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.stop /path/where/docker-compose/stored
salt myminion dockercompose.stop /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
def pause(path, service_names=None):
'''
Pause running containers in the docker-compose file, service_names is a python
list, if omitted pause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.pause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'paused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pausing containers via docker-compose', result, debug_ret)
def unpause(path, service_names=None):
'''
Un-Pause containers in the docker-compose file, service_names is a python
list, if omitted unpause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will un-pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.unpause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'unpaused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Un-Pausing containers via docker-compose', result, debug_ret)
def start(path, service_names=None):
'''
Start containers in the docker-compose file, service_names is a python
list, if omitted start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.start /path/where/docker-compose/stored
salt myminion dockercompose.start /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.start(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'started'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Starting containers via docker-compose', result, debug_ret)
def kill(path, service_names=None):
'''
Kill containers in the docker-compose file, service_names is a python
list, if omitted kill all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will kill only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.kill /path/where/docker-compose/stored
salt myminion dockercompose.kill /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.kill(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'killed'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Killing containers via docker-compose', result, debug_ret)
def rm(path, service_names=None):
'''
Remove stopped containers in the docker-compose file, service_names is a python
list, if omitted remove all stopped containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will remove only the specified stopped services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.rm /path/where/docker-compose/stored
salt myminion dockercompose.rm /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.remove_stopped(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Removing stopped containers via docker-compose', None, None)
def ps(path):
'''
List all running containers and report some information about them
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.ps /path/where/docker-compose/stored
'''
project = __load_project(path)
result = {}
if isinstance(project, dict):
return project
else:
if USE_FILTERCLASS:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, OneOffFilter.only),
key=attrgetter('name'))
else:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, one_off=True),
key=attrgetter('name'))
for container in containers:
command = container.human_readable_command
if len(command) > 30:
command = '{0} ...'.format(command[:26])
result[container.name] = {
'id': container.id,
'name': container.name,
'command': command,
'state': container.human_readable_state,
'ports': container.human_readable_ports,
}
return __standardize_result(True, 'Listing docker-compose containers', result, None)
def up(path, service_names=None):
'''
Create and start containers defined in the docker-compose.yml file
located in path, service_names is a python list, if omitted create and
start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will create and start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.up /path/where/docker-compose/stored
salt myminion dockercompose.up /path/where/docker-compose/stored '[janus]'
'''
debug_ret = {}
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
result = _get_convergence_plans(project, service_names)
ret = project.up(service_names)
if debug:
for container in ret:
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Adding containers via docker-compose', result, debug_ret)
def service_create(path, service_name, definition):
'''
Create the definition of a docker-compose service
This fails when the service already exists
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service {0} created'.format(service_name),
already_existed=True)
def service_upsert(path, service_name, definition):
'''
Create or update the definition of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_upsert /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service definition for {0} is set'.format(service_name),
already_existed=True)
def service_remove(path, service_name):
'''
Remove the definition of a docker-compose service
This does not rm the container
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_remove /path/where/docker-compose/stored service_name
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
del services[service_name]
return __dump_compose_file(path, compose_result,
'Service {0} is removed from {1}'.format(service_name, path),
already_existed=True)
def service_set_tag(path, service_name, tag):
'''
Change the tag of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
tag
Name of the tag (often used as version) that the service image should have
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name tag
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
if 'image' not in services[service_name]:
return __standardize_result(False,
'Service {0} did not contain the variable "image"'.format(service_name),
None, None)
image = services[service_name]['image'].split(':')[0]
services[service_name]['image'] = '{0}:{1}'.format(image, tag)
return __dump_compose_file(path, compose_result,
'Service {0} is set to tag "{1}"'.format(service_name, tag),
already_existed=True)
|
saltstack/salt
|
salt/modules/dockercompose.py
|
create
|
python
|
def create(path, docker_compose):
'''
Create and validate a docker-compose file into a directory
path
Path where the docker-compose file will be stored on the server
docker_compose
docker_compose file
CLI Example:
.. code-block:: bash
salt myminion dockercompose.create /path/where/docker-compose/stored content
'''
if docker_compose:
ret = __write_docker_compose(path,
docker_compose,
already_existed=False)
if isinstance(ret, dict):
return ret
else:
return __standardize_result(False,
'Creating a docker-compose project failed, you must send a valid docker-compose file',
None, None)
return __standardize_result(True,
'Successfully created the docker-compose file',
{'compose.base_dir': path},
None)
|
Create and validate a docker-compose file into a directory
path
Path where the docker-compose file will be stored on the server
docker_compose
docker_compose file
CLI Example:
.. code-block:: bash
salt myminion dockercompose.create /path/where/docker-compose/stored content
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockercompose.py#L466-L495
|
[
"def __standardize_result(status, message, data=None, debug_msg=None):\n '''\n Standardizes all responses\n\n :param status:\n :param message:\n :param data:\n :param debug_msg:\n :return:\n '''\n result = {\n 'status': status,\n 'message': message\n }\n\n if data is not None:\n result['return'] = data\n\n if debug_msg is not None and debug:\n result['debug'] = debug_msg\n\n return result\n",
"def __write_docker_compose(path, docker_compose, already_existed):\n '''\n Write docker-compose to a path\n in order to use it with docker-compose ( config check )\n\n :param path:\n\n docker_compose\n contains the docker-compose file\n\n :return:\n '''\n if path.lower().endswith(('.yml', '.yaml')):\n file_path = path\n dir_name = os.path.dirname(path)\n else:\n dir_name = path\n file_path = os.path.join(dir_name, DEFAULT_DC_FILENAMES[0])\n if os.path.isdir(dir_name) is False:\n os.mkdir(dir_name)\n try:\n with salt.utils.files.fopen(file_path, 'w') as fl:\n fl.write(salt.utils.stringutils.to_str(docker_compose))\n except EnvironmentError:\n return __standardize_result(False,\n 'Could not write {0}'.format(file_path),\n None, None)\n project = __load_project_from_file_path(file_path)\n if isinstance(project, dict):\n if not already_existed:\n os.remove(file_path)\n return project\n return file_path\n"
] |
# -*- coding: utf-8 -*-
'''
Module to import docker-compose via saltstack
.. versionadded:: 2016.3.0
:maintainer: Jean Praloran <jeanpralo@gmail.com>
:maturity: new
:depends: docker-compose>=1.5
:platform: all
Introduction
------------
This module allows one to deal with docker-compose file in a directory.
This is a first version only, the following commands are missing at the moment
but will be built later on if the community is interested in this module:
- run
- logs
- port
- scale
Installation Prerequisites
--------------------------
This execution module requires at least version 1.4.0 of both docker-compose_ and
Docker_. docker-compose can easily be installed using :py:func:`pip.install
<salt.modules.pip.install>`:
.. code-block:: bash
salt myminion pip.install docker-compose>=1.5.0
.. _docker-compose: https://pypi.python.org/pypi/docker-compose
.. _Docker: https://www.docker.com/
How to use this module?
-----------------------
In order to use the module if you have no docker-compose file on the server you
can issue the command create, it takes two arguments the path where the
docker-compose.yml will be stored and the content of this latter:
.. code-block:: text
# salt-call -l debug dockercompose.create /tmp/toto '
database:
image: mongo:3.0
command: mongod --smallfiles --quiet --logpath=/dev/null
'
Then you can execute a list of method defined at the bottom with at least one
argument (the path where the docker-compose.yml will be read) and an optional
python list which corresponds to the services names:
.. code-block:: bash
# salt-call -l debug dockercompose.up /tmp/toto
# salt-call -l debug dockercompose.restart /tmp/toto '[database]'
# salt-call -l debug dockercompose.stop /tmp/toto
# salt-call -l debug dockercompose.rm /tmp/toto
Docker-compose method supported
-------------------------------
- up
- restart
- stop
- start
- pause
- unpause
- kill
- rm
- ps
- pull
- build
Functions
---------
- docker-compose.yml management
- :py:func:`dockercompose.create <salt.modules.dockercompose.create>`
- :py:func:`dockercompose.get <salt.modules.dockercompose.get>`
- Manage containers
- :py:func:`dockercompose.restart <salt.modules.dockercompose.restart>`
- :py:func:`dockercompose.stop <salt.modules.dockercompose.stop>`
- :py:func:`dockercompose.pause <salt.modules.dockercompose.pause>`
- :py:func:`dockercompose.unpause <salt.modules.dockercompose.unpause>`
- :py:func:`dockercompose.start <salt.modules.dockercompose.start>`
- :py:func:`dockercompose.kill <salt.modules.dockercompose.kill>`
- :py:func:`dockercompose.rm <salt.modules.dockercompose.rm>`
- :py:func:`dockercompose.up <salt.modules.dockercompose.up>`
- Manage containers image:
- :py:func:`dockercompose.pull <salt.modules.dockercompose.pull>`
- :py:func:`dockercompose.build <salt.modules.dockercompose.build>`
- Gather information about containers:
- :py:func:`dockercompose.ps <salt.modules.dockercompose.ps>`
- Manage service definitions:
- :py:func:`dockercompose.service_create <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_upsert <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_remove <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_set_tag <salt.modules.dockercompose.ps>`
Detailed Function Documentation
-------------------------------
'''
from __future__ import absolute_import, print_function, unicode_literals
import inspect
import logging
import os
import re
import salt.utils.files
import salt.utils.stringutils
from salt.ext import six
from operator import attrgetter
from salt.serializers import json
from salt.utils import yaml
try:
import compose
from compose.cli.command import get_project
from compose.service import ConvergenceStrategy
HAS_DOCKERCOMPOSE = True
except ImportError:
HAS_DOCKERCOMPOSE = False
try:
from compose.project import OneOffFilter
USE_FILTERCLASS = True
except ImportError:
USE_FILTERCLASS = False
MIN_DOCKERCOMPOSE = (1, 5, 0)
VERSION_RE = r'([\d.]+)'
log = logging.getLogger(__name__)
debug = False
__virtualname__ = 'dockercompose'
DEFAULT_DC_FILENAMES = ('docker-compose.yml', 'docker-compose.yaml')
def __virtual__():
if HAS_DOCKERCOMPOSE:
match = re.match(VERSION_RE, six.text_type(compose.__version__))
if match:
version = tuple([int(x) for x in match.group(1).split('.')])
if version >= MIN_DOCKERCOMPOSE:
return __virtualname__
return (False, 'The dockercompose execution module not loaded: '
'compose python library not available.')
def __standardize_result(status, message, data=None, debug_msg=None):
'''
Standardizes all responses
:param status:
:param message:
:param data:
:param debug_msg:
:return:
'''
result = {
'status': status,
'message': message
}
if data is not None:
result['return'] = data
if debug_msg is not None and debug:
result['debug'] = debug_msg
return result
def __get_docker_file_path(path):
'''
Determines the filepath to use
:param path:
:return:
'''
if os.path.isfile(path):
return path
for dc_filename in DEFAULT_DC_FILENAMES:
file_path = os.path.join(path, dc_filename)
if os.path.isfile(file_path):
return file_path
# implicitly return None
def __read_docker_compose_file(file_path):
'''
Read the compose file if it exists in the directory
:param file_path:
:return:
'''
if not os.path.isfile(file_path):
return __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
file_name = os.path.basename(file_path)
result = {file_name: ''}
for line in fl:
result[file_name] += salt.utils.stringutils.to_unicode(line)
except EnvironmentError:
return __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
return __standardize_result(True,
'Reading content of {0}'.format(file_path),
result, None)
def __load_docker_compose(path):
'''
Read the compose file and load its' contents
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return None, __standardize_result(False, msg,
None, None)
if not os.path.isfile(file_path):
return None, __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
loaded = yaml.load(fl)
except EnvironmentError:
return None, __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(file_path, yerr)
return None, __standardize_result(False, msg,
None, None)
if not loaded:
msg = 'Got empty compose file at {0}'.format(file_path)
return None, __standardize_result(False, msg,
None, None)
if 'services' not in loaded:
loaded['services'] = {}
result = {
'compose_content': loaded,
'file_name': os.path.basename(file_path)
}
return result, None
def __dump_docker_compose(path, content, already_existed):
'''
Dumps
:param path:
:param content: the not-yet dumped content
:return:
'''
try:
dumped = yaml.safe_dump(content, indent=2, default_flow_style=False)
return __write_docker_compose(path, dumped, already_existed)
except TypeError as t_err:
msg = 'Could not dump {0} {1}'.format(content, t_err)
return __standardize_result(False, msg,
None, None)
def __write_docker_compose(path, docker_compose, already_existed):
'''
Write docker-compose to a path
in order to use it with docker-compose ( config check )
:param path:
docker_compose
contains the docker-compose file
:return:
'''
if path.lower().endswith(('.yml', '.yaml')):
file_path = path
dir_name = os.path.dirname(path)
else:
dir_name = path
file_path = os.path.join(dir_name, DEFAULT_DC_FILENAMES[0])
if os.path.isdir(dir_name) is False:
os.mkdir(dir_name)
try:
with salt.utils.files.fopen(file_path, 'w') as fl:
fl.write(salt.utils.stringutils.to_str(docker_compose))
except EnvironmentError:
return __standardize_result(False,
'Could not write {0}'.format(file_path),
None, None)
project = __load_project_from_file_path(file_path)
if isinstance(project, dict):
if not already_existed:
os.remove(file_path)
return project
return file_path
def __load_project(path):
'''
Load a docker-compose project from path
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return __standardize_result(False,
msg,
None, None)
return __load_project_from_file_path(file_path)
def __load_project_from_file_path(file_path):
'''
Load a docker-compose project from file path
:param path:
:return:
'''
try:
project = get_project(project_dir=os.path.dirname(file_path),
config_path=[os.path.basename(file_path)])
except Exception as inst:
return __handle_except(inst)
return project
def __load_compose_definitions(path, definition):
'''
Will load the compose file located at path
Then determines the format/contents of the sent definition
err or results are only set if there were any
:param path:
:param definition:
:return tuple(compose_result, loaded_definition, err):
'''
compose_result, err = __load_docker_compose(path)
if err:
return None, None, err
if isinstance(definition, dict):
return compose_result, definition, None
elif definition.strip().startswith('{'):
try:
loaded_definition = json.deserialize(definition)
except json.DeserializationError as jerr:
msg = 'Could not parse {0} {1}'.format(definition, jerr)
return None, None, __standardize_result(False, msg,
None, None)
else:
try:
loaded_definition = yaml.load(definition)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(definition, yerr)
return None, None, __standardize_result(False, msg,
None, None)
return compose_result, loaded_definition, None
def __dump_compose_file(path, compose_result, success_msg, already_existed):
'''
Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return:
'''
ret = __dump_docker_compose(path,
compose_result['compose_content'],
already_existed)
if isinstance(ret, dict):
return ret
return __standardize_result(True, success_msg,
compose_result['compose_content'], None)
def __handle_except(inst):
'''
Handle exception and return a standard result
:param inst:
:return:
'''
return __standardize_result(False,
'Docker-compose command {0} failed'.
format(inspect.stack()[1][3]),
'{0}'.format(inst), None)
def _get_convergence_plans(project, service_names):
'''
Get action executed for each container
:param project:
:param service_names:
:return:
'''
ret = {}
plans = project._get_convergence_plans(project.get_services(service_names),
ConvergenceStrategy.changed)
for cont in plans:
(action, container) = plans[cont]
if action == 'create':
ret[cont] = 'Creating container'
elif action == 'recreate':
ret[cont] = 'Re-creating container'
elif action == 'start':
ret[cont] = 'Starting container'
elif action == 'noop':
ret[cont] = 'Container is up to date'
return ret
def get(path):
'''
Get the content of the docker-compose file into a directory
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.get /path/where/docker-compose/stored
'''
file_path = __get_docker_file_path(path)
if file_path is None:
return __standardize_result(False,
'Path {} is not present'.format(path),
None, None)
salt_result = __read_docker_compose_file(file_path)
if not salt_result['status']:
return salt_result
project = __load_project(path)
if isinstance(project, dict):
salt_result['return']['valid'] = False
else:
salt_result['return']['valid'] = True
return salt_result
def pull(path, service_names=None):
'''
Pull image for containers in the docker-compose file, service_names is a
python list, if omitted pull all images
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pull /path/where/docker-compose/stored
salt myminion dockercompose.pull /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.pull(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pulling containers images via docker-compose succeeded',
None, None)
def build(path, service_names=None):
'''
Build image for containers in the docker-compose file, service_names is a
python list, if omitted build images for all containers. Please note
that at the moment the module does not allow you to upload your Dockerfile,
nor any other file you could need with your docker-compose.yml, you will
have to make sure the files you need are actually in the directory specified
in the `build` keyword
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.build /path/where/docker-compose/stored
salt myminion dockercompose.build /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.build(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Building containers images via docker-compose succeeded',
None, None)
def restart(path, service_names=None):
'''
Restart container(s) in the docker-compose file, service_names is a python
list, if omitted restart all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will restart only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.restart /path/where/docker-compose/stored
salt myminion dockercompose.restart /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.restart(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'restarted'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Restarting containers via docker-compose', result, debug_ret)
def stop(path, service_names=None):
'''
Stop running containers in the docker-compose file, service_names is a python
list, if omitted stop all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will stop only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.stop /path/where/docker-compose/stored
salt myminion dockercompose.stop /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
def pause(path, service_names=None):
'''
Pause running containers in the docker-compose file, service_names is a python
list, if omitted pause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.pause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'paused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pausing containers via docker-compose', result, debug_ret)
def unpause(path, service_names=None):
'''
Un-Pause containers in the docker-compose file, service_names is a python
list, if omitted unpause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will un-pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.unpause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'unpaused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Un-Pausing containers via docker-compose', result, debug_ret)
def start(path, service_names=None):
'''
Start containers in the docker-compose file, service_names is a python
list, if omitted start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.start /path/where/docker-compose/stored
salt myminion dockercompose.start /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.start(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'started'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Starting containers via docker-compose', result, debug_ret)
def kill(path, service_names=None):
'''
Kill containers in the docker-compose file, service_names is a python
list, if omitted kill all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will kill only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.kill /path/where/docker-compose/stored
salt myminion dockercompose.kill /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.kill(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'killed'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Killing containers via docker-compose', result, debug_ret)
def rm(path, service_names=None):
'''
Remove stopped containers in the docker-compose file, service_names is a python
list, if omitted remove all stopped containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will remove only the specified stopped services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.rm /path/where/docker-compose/stored
salt myminion dockercompose.rm /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.remove_stopped(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Removing stopped containers via docker-compose', None, None)
def ps(path):
'''
List all running containers and report some information about them
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.ps /path/where/docker-compose/stored
'''
project = __load_project(path)
result = {}
if isinstance(project, dict):
return project
else:
if USE_FILTERCLASS:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, OneOffFilter.only),
key=attrgetter('name'))
else:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, one_off=True),
key=attrgetter('name'))
for container in containers:
command = container.human_readable_command
if len(command) > 30:
command = '{0} ...'.format(command[:26])
result[container.name] = {
'id': container.id,
'name': container.name,
'command': command,
'state': container.human_readable_state,
'ports': container.human_readable_ports,
}
return __standardize_result(True, 'Listing docker-compose containers', result, None)
def up(path, service_names=None):
'''
Create and start containers defined in the docker-compose.yml file
located in path, service_names is a python list, if omitted create and
start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will create and start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.up /path/where/docker-compose/stored
salt myminion dockercompose.up /path/where/docker-compose/stored '[janus]'
'''
debug_ret = {}
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
result = _get_convergence_plans(project, service_names)
ret = project.up(service_names)
if debug:
for container in ret:
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Adding containers via docker-compose', result, debug_ret)
def service_create(path, service_name, definition):
'''
Create the definition of a docker-compose service
This fails when the service already exists
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service {0} created'.format(service_name),
already_existed=True)
def service_upsert(path, service_name, definition):
'''
Create or update the definition of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_upsert /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service definition for {0} is set'.format(service_name),
already_existed=True)
def service_remove(path, service_name):
'''
Remove the definition of a docker-compose service
This does not rm the container
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_remove /path/where/docker-compose/stored service_name
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
del services[service_name]
return __dump_compose_file(path, compose_result,
'Service {0} is removed from {1}'.format(service_name, path),
already_existed=True)
def service_set_tag(path, service_name, tag):
'''
Change the tag of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
tag
Name of the tag (often used as version) that the service image should have
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name tag
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
if 'image' not in services[service_name]:
return __standardize_result(False,
'Service {0} did not contain the variable "image"'.format(service_name),
None, None)
image = services[service_name]['image'].split(':')[0]
services[service_name]['image'] = '{0}:{1}'.format(image, tag)
return __dump_compose_file(path, compose_result,
'Service {0} is set to tag "{1}"'.format(service_name, tag),
already_existed=True)
|
saltstack/salt
|
salt/modules/dockercompose.py
|
pull
|
python
|
def pull(path, service_names=None):
'''
Pull image for containers in the docker-compose file, service_names is a
python list, if omitted pull all images
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pull /path/where/docker-compose/stored
salt myminion dockercompose.pull /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.pull(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pulling containers images via docker-compose succeeded',
None, None)
|
Pull image for containers in the docker-compose file, service_names is a
python list, if omitted pull all images
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pull /path/where/docker-compose/stored
salt myminion dockercompose.pull /path/where/docker-compose/stored '[janus]'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockercompose.py#L498-L525
|
[
"def __standardize_result(status, message, data=None, debug_msg=None):\n '''\n Standardizes all responses\n\n :param status:\n :param message:\n :param data:\n :param debug_msg:\n :return:\n '''\n result = {\n 'status': status,\n 'message': message\n }\n\n if data is not None:\n result['return'] = data\n\n if debug_msg is not None and debug:\n result['debug'] = debug_msg\n\n return result\n",
"def __load_project(path):\n '''\n Load a docker-compose project from path\n\n :param path:\n :return:\n '''\n file_path = __get_docker_file_path(path)\n if file_path is None:\n msg = 'Could not find docker-compose file at {0}'.format(path)\n return __standardize_result(False,\n msg,\n None, None)\n return __load_project_from_file_path(file_path)\n",
"def __handle_except(inst):\n '''\n Handle exception and return a standard result\n\n :param inst:\n :return:\n '''\n return __standardize_result(False,\n 'Docker-compose command {0} failed'.\n format(inspect.stack()[1][3]),\n '{0}'.format(inst), None)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to import docker-compose via saltstack
.. versionadded:: 2016.3.0
:maintainer: Jean Praloran <jeanpralo@gmail.com>
:maturity: new
:depends: docker-compose>=1.5
:platform: all
Introduction
------------
This module allows one to deal with docker-compose file in a directory.
This is a first version only, the following commands are missing at the moment
but will be built later on if the community is interested in this module:
- run
- logs
- port
- scale
Installation Prerequisites
--------------------------
This execution module requires at least version 1.4.0 of both docker-compose_ and
Docker_. docker-compose can easily be installed using :py:func:`pip.install
<salt.modules.pip.install>`:
.. code-block:: bash
salt myminion pip.install docker-compose>=1.5.0
.. _docker-compose: https://pypi.python.org/pypi/docker-compose
.. _Docker: https://www.docker.com/
How to use this module?
-----------------------
In order to use the module if you have no docker-compose file on the server you
can issue the command create, it takes two arguments the path where the
docker-compose.yml will be stored and the content of this latter:
.. code-block:: text
# salt-call -l debug dockercompose.create /tmp/toto '
database:
image: mongo:3.0
command: mongod --smallfiles --quiet --logpath=/dev/null
'
Then you can execute a list of method defined at the bottom with at least one
argument (the path where the docker-compose.yml will be read) and an optional
python list which corresponds to the services names:
.. code-block:: bash
# salt-call -l debug dockercompose.up /tmp/toto
# salt-call -l debug dockercompose.restart /tmp/toto '[database]'
# salt-call -l debug dockercompose.stop /tmp/toto
# salt-call -l debug dockercompose.rm /tmp/toto
Docker-compose method supported
-------------------------------
- up
- restart
- stop
- start
- pause
- unpause
- kill
- rm
- ps
- pull
- build
Functions
---------
- docker-compose.yml management
- :py:func:`dockercompose.create <salt.modules.dockercompose.create>`
- :py:func:`dockercompose.get <salt.modules.dockercompose.get>`
- Manage containers
- :py:func:`dockercompose.restart <salt.modules.dockercompose.restart>`
- :py:func:`dockercompose.stop <salt.modules.dockercompose.stop>`
- :py:func:`dockercompose.pause <salt.modules.dockercompose.pause>`
- :py:func:`dockercompose.unpause <salt.modules.dockercompose.unpause>`
- :py:func:`dockercompose.start <salt.modules.dockercompose.start>`
- :py:func:`dockercompose.kill <salt.modules.dockercompose.kill>`
- :py:func:`dockercompose.rm <salt.modules.dockercompose.rm>`
- :py:func:`dockercompose.up <salt.modules.dockercompose.up>`
- Manage containers image:
- :py:func:`dockercompose.pull <salt.modules.dockercompose.pull>`
- :py:func:`dockercompose.build <salt.modules.dockercompose.build>`
- Gather information about containers:
- :py:func:`dockercompose.ps <salt.modules.dockercompose.ps>`
- Manage service definitions:
- :py:func:`dockercompose.service_create <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_upsert <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_remove <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_set_tag <salt.modules.dockercompose.ps>`
Detailed Function Documentation
-------------------------------
'''
from __future__ import absolute_import, print_function, unicode_literals
import inspect
import logging
import os
import re
import salt.utils.files
import salt.utils.stringutils
from salt.ext import six
from operator import attrgetter
from salt.serializers import json
from salt.utils import yaml
try:
import compose
from compose.cli.command import get_project
from compose.service import ConvergenceStrategy
HAS_DOCKERCOMPOSE = True
except ImportError:
HAS_DOCKERCOMPOSE = False
try:
from compose.project import OneOffFilter
USE_FILTERCLASS = True
except ImportError:
USE_FILTERCLASS = False
MIN_DOCKERCOMPOSE = (1, 5, 0)
VERSION_RE = r'([\d.]+)'
log = logging.getLogger(__name__)
debug = False
__virtualname__ = 'dockercompose'
DEFAULT_DC_FILENAMES = ('docker-compose.yml', 'docker-compose.yaml')
def __virtual__():
if HAS_DOCKERCOMPOSE:
match = re.match(VERSION_RE, six.text_type(compose.__version__))
if match:
version = tuple([int(x) for x in match.group(1).split('.')])
if version >= MIN_DOCKERCOMPOSE:
return __virtualname__
return (False, 'The dockercompose execution module not loaded: '
'compose python library not available.')
def __standardize_result(status, message, data=None, debug_msg=None):
'''
Standardizes all responses
:param status:
:param message:
:param data:
:param debug_msg:
:return:
'''
result = {
'status': status,
'message': message
}
if data is not None:
result['return'] = data
if debug_msg is not None and debug:
result['debug'] = debug_msg
return result
def __get_docker_file_path(path):
'''
Determines the filepath to use
:param path:
:return:
'''
if os.path.isfile(path):
return path
for dc_filename in DEFAULT_DC_FILENAMES:
file_path = os.path.join(path, dc_filename)
if os.path.isfile(file_path):
return file_path
# implicitly return None
def __read_docker_compose_file(file_path):
'''
Read the compose file if it exists in the directory
:param file_path:
:return:
'''
if not os.path.isfile(file_path):
return __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
file_name = os.path.basename(file_path)
result = {file_name: ''}
for line in fl:
result[file_name] += salt.utils.stringutils.to_unicode(line)
except EnvironmentError:
return __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
return __standardize_result(True,
'Reading content of {0}'.format(file_path),
result, None)
def __load_docker_compose(path):
'''
Read the compose file and load its' contents
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return None, __standardize_result(False, msg,
None, None)
if not os.path.isfile(file_path):
return None, __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
loaded = yaml.load(fl)
except EnvironmentError:
return None, __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(file_path, yerr)
return None, __standardize_result(False, msg,
None, None)
if not loaded:
msg = 'Got empty compose file at {0}'.format(file_path)
return None, __standardize_result(False, msg,
None, None)
if 'services' not in loaded:
loaded['services'] = {}
result = {
'compose_content': loaded,
'file_name': os.path.basename(file_path)
}
return result, None
def __dump_docker_compose(path, content, already_existed):
'''
Dumps
:param path:
:param content: the not-yet dumped content
:return:
'''
try:
dumped = yaml.safe_dump(content, indent=2, default_flow_style=False)
return __write_docker_compose(path, dumped, already_existed)
except TypeError as t_err:
msg = 'Could not dump {0} {1}'.format(content, t_err)
return __standardize_result(False, msg,
None, None)
def __write_docker_compose(path, docker_compose, already_existed):
'''
Write docker-compose to a path
in order to use it with docker-compose ( config check )
:param path:
docker_compose
contains the docker-compose file
:return:
'''
if path.lower().endswith(('.yml', '.yaml')):
file_path = path
dir_name = os.path.dirname(path)
else:
dir_name = path
file_path = os.path.join(dir_name, DEFAULT_DC_FILENAMES[0])
if os.path.isdir(dir_name) is False:
os.mkdir(dir_name)
try:
with salt.utils.files.fopen(file_path, 'w') as fl:
fl.write(salt.utils.stringutils.to_str(docker_compose))
except EnvironmentError:
return __standardize_result(False,
'Could not write {0}'.format(file_path),
None, None)
project = __load_project_from_file_path(file_path)
if isinstance(project, dict):
if not already_existed:
os.remove(file_path)
return project
return file_path
def __load_project(path):
'''
Load a docker-compose project from path
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return __standardize_result(False,
msg,
None, None)
return __load_project_from_file_path(file_path)
def __load_project_from_file_path(file_path):
'''
Load a docker-compose project from file path
:param path:
:return:
'''
try:
project = get_project(project_dir=os.path.dirname(file_path),
config_path=[os.path.basename(file_path)])
except Exception as inst:
return __handle_except(inst)
return project
def __load_compose_definitions(path, definition):
'''
Will load the compose file located at path
Then determines the format/contents of the sent definition
err or results are only set if there were any
:param path:
:param definition:
:return tuple(compose_result, loaded_definition, err):
'''
compose_result, err = __load_docker_compose(path)
if err:
return None, None, err
if isinstance(definition, dict):
return compose_result, definition, None
elif definition.strip().startswith('{'):
try:
loaded_definition = json.deserialize(definition)
except json.DeserializationError as jerr:
msg = 'Could not parse {0} {1}'.format(definition, jerr)
return None, None, __standardize_result(False, msg,
None, None)
else:
try:
loaded_definition = yaml.load(definition)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(definition, yerr)
return None, None, __standardize_result(False, msg,
None, None)
return compose_result, loaded_definition, None
def __dump_compose_file(path, compose_result, success_msg, already_existed):
'''
Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return:
'''
ret = __dump_docker_compose(path,
compose_result['compose_content'],
already_existed)
if isinstance(ret, dict):
return ret
return __standardize_result(True, success_msg,
compose_result['compose_content'], None)
def __handle_except(inst):
'''
Handle exception and return a standard result
:param inst:
:return:
'''
return __standardize_result(False,
'Docker-compose command {0} failed'.
format(inspect.stack()[1][3]),
'{0}'.format(inst), None)
def _get_convergence_plans(project, service_names):
'''
Get action executed for each container
:param project:
:param service_names:
:return:
'''
ret = {}
plans = project._get_convergence_plans(project.get_services(service_names),
ConvergenceStrategy.changed)
for cont in plans:
(action, container) = plans[cont]
if action == 'create':
ret[cont] = 'Creating container'
elif action == 'recreate':
ret[cont] = 'Re-creating container'
elif action == 'start':
ret[cont] = 'Starting container'
elif action == 'noop':
ret[cont] = 'Container is up to date'
return ret
def get(path):
'''
Get the content of the docker-compose file into a directory
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.get /path/where/docker-compose/stored
'''
file_path = __get_docker_file_path(path)
if file_path is None:
return __standardize_result(False,
'Path {} is not present'.format(path),
None, None)
salt_result = __read_docker_compose_file(file_path)
if not salt_result['status']:
return salt_result
project = __load_project(path)
if isinstance(project, dict):
salt_result['return']['valid'] = False
else:
salt_result['return']['valid'] = True
return salt_result
def create(path, docker_compose):
'''
Create and validate a docker-compose file into a directory
path
Path where the docker-compose file will be stored on the server
docker_compose
docker_compose file
CLI Example:
.. code-block:: bash
salt myminion dockercompose.create /path/where/docker-compose/stored content
'''
if docker_compose:
ret = __write_docker_compose(path,
docker_compose,
already_existed=False)
if isinstance(ret, dict):
return ret
else:
return __standardize_result(False,
'Creating a docker-compose project failed, you must send a valid docker-compose file',
None, None)
return __standardize_result(True,
'Successfully created the docker-compose file',
{'compose.base_dir': path},
None)
def build(path, service_names=None):
'''
Build image for containers in the docker-compose file, service_names is a
python list, if omitted build images for all containers. Please note
that at the moment the module does not allow you to upload your Dockerfile,
nor any other file you could need with your docker-compose.yml, you will
have to make sure the files you need are actually in the directory specified
in the `build` keyword
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.build /path/where/docker-compose/stored
salt myminion dockercompose.build /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.build(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Building containers images via docker-compose succeeded',
None, None)
def restart(path, service_names=None):
'''
Restart container(s) in the docker-compose file, service_names is a python
list, if omitted restart all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will restart only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.restart /path/where/docker-compose/stored
salt myminion dockercompose.restart /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.restart(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'restarted'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Restarting containers via docker-compose', result, debug_ret)
def stop(path, service_names=None):
'''
Stop running containers in the docker-compose file, service_names is a python
list, if omitted stop all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will stop only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.stop /path/where/docker-compose/stored
salt myminion dockercompose.stop /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
def pause(path, service_names=None):
'''
Pause running containers in the docker-compose file, service_names is a python
list, if omitted pause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.pause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'paused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pausing containers via docker-compose', result, debug_ret)
def unpause(path, service_names=None):
'''
Un-Pause containers in the docker-compose file, service_names is a python
list, if omitted unpause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will un-pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.unpause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'unpaused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Un-Pausing containers via docker-compose', result, debug_ret)
def start(path, service_names=None):
'''
Start containers in the docker-compose file, service_names is a python
list, if omitted start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.start /path/where/docker-compose/stored
salt myminion dockercompose.start /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.start(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'started'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Starting containers via docker-compose', result, debug_ret)
def kill(path, service_names=None):
'''
Kill containers in the docker-compose file, service_names is a python
list, if omitted kill all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will kill only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.kill /path/where/docker-compose/stored
salt myminion dockercompose.kill /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.kill(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'killed'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Killing containers via docker-compose', result, debug_ret)
def rm(path, service_names=None):
'''
Remove stopped containers in the docker-compose file, service_names is a python
list, if omitted remove all stopped containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will remove only the specified stopped services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.rm /path/where/docker-compose/stored
salt myminion dockercompose.rm /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.remove_stopped(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Removing stopped containers via docker-compose', None, None)
def ps(path):
'''
List all running containers and report some information about them
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.ps /path/where/docker-compose/stored
'''
project = __load_project(path)
result = {}
if isinstance(project, dict):
return project
else:
if USE_FILTERCLASS:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, OneOffFilter.only),
key=attrgetter('name'))
else:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, one_off=True),
key=attrgetter('name'))
for container in containers:
command = container.human_readable_command
if len(command) > 30:
command = '{0} ...'.format(command[:26])
result[container.name] = {
'id': container.id,
'name': container.name,
'command': command,
'state': container.human_readable_state,
'ports': container.human_readable_ports,
}
return __standardize_result(True, 'Listing docker-compose containers', result, None)
def up(path, service_names=None):
'''
Create and start containers defined in the docker-compose.yml file
located in path, service_names is a python list, if omitted create and
start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will create and start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.up /path/where/docker-compose/stored
salt myminion dockercompose.up /path/where/docker-compose/stored '[janus]'
'''
debug_ret = {}
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
result = _get_convergence_plans(project, service_names)
ret = project.up(service_names)
if debug:
for container in ret:
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Adding containers via docker-compose', result, debug_ret)
def service_create(path, service_name, definition):
'''
Create the definition of a docker-compose service
This fails when the service already exists
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service {0} created'.format(service_name),
already_existed=True)
def service_upsert(path, service_name, definition):
'''
Create or update the definition of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_upsert /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service definition for {0} is set'.format(service_name),
already_existed=True)
def service_remove(path, service_name):
'''
Remove the definition of a docker-compose service
This does not rm the container
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_remove /path/where/docker-compose/stored service_name
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
del services[service_name]
return __dump_compose_file(path, compose_result,
'Service {0} is removed from {1}'.format(service_name, path),
already_existed=True)
def service_set_tag(path, service_name, tag):
'''
Change the tag of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
tag
Name of the tag (often used as version) that the service image should have
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name tag
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
if 'image' not in services[service_name]:
return __standardize_result(False,
'Service {0} did not contain the variable "image"'.format(service_name),
None, None)
image = services[service_name]['image'].split(':')[0]
services[service_name]['image'] = '{0}:{1}'.format(image, tag)
return __dump_compose_file(path, compose_result,
'Service {0} is set to tag "{1}"'.format(service_name, tag),
already_existed=True)
|
saltstack/salt
|
salt/modules/dockercompose.py
|
pause
|
python
|
def pause(path, service_names=None):
'''
Pause running containers in the docker-compose file, service_names is a python
list, if omitted pause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.pause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'paused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pausing containers via docker-compose', result, debug_ret)
|
Pause running containers in the docker-compose file, service_names is a python
list, if omitted pause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockercompose.py#L637-L671
|
[
"def __standardize_result(status, message, data=None, debug_msg=None):\n '''\n Standardizes all responses\n\n :param status:\n :param message:\n :param data:\n :param debug_msg:\n :return:\n '''\n result = {\n 'status': status,\n 'message': message\n }\n\n if data is not None:\n result['return'] = data\n\n if debug_msg is not None and debug:\n result['debug'] = debug_msg\n\n return result\n",
"def __load_project(path):\n '''\n Load a docker-compose project from path\n\n :param path:\n :return:\n '''\n file_path = __get_docker_file_path(path)\n if file_path is None:\n msg = 'Could not find docker-compose file at {0}'.format(path)\n return __standardize_result(False,\n msg,\n None, None)\n return __load_project_from_file_path(file_path)\n",
"def __handle_except(inst):\n '''\n Handle exception and return a standard result\n\n :param inst:\n :return:\n '''\n return __standardize_result(False,\n 'Docker-compose command {0} failed'.\n format(inspect.stack()[1][3]),\n '{0}'.format(inst), None)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to import docker-compose via saltstack
.. versionadded:: 2016.3.0
:maintainer: Jean Praloran <jeanpralo@gmail.com>
:maturity: new
:depends: docker-compose>=1.5
:platform: all
Introduction
------------
This module allows one to deal with docker-compose file in a directory.
This is a first version only, the following commands are missing at the moment
but will be built later on if the community is interested in this module:
- run
- logs
- port
- scale
Installation Prerequisites
--------------------------
This execution module requires at least version 1.4.0 of both docker-compose_ and
Docker_. docker-compose can easily be installed using :py:func:`pip.install
<salt.modules.pip.install>`:
.. code-block:: bash
salt myminion pip.install docker-compose>=1.5.0
.. _docker-compose: https://pypi.python.org/pypi/docker-compose
.. _Docker: https://www.docker.com/
How to use this module?
-----------------------
In order to use the module if you have no docker-compose file on the server you
can issue the command create, it takes two arguments the path where the
docker-compose.yml will be stored and the content of this latter:
.. code-block:: text
# salt-call -l debug dockercompose.create /tmp/toto '
database:
image: mongo:3.0
command: mongod --smallfiles --quiet --logpath=/dev/null
'
Then you can execute a list of method defined at the bottom with at least one
argument (the path where the docker-compose.yml will be read) and an optional
python list which corresponds to the services names:
.. code-block:: bash
# salt-call -l debug dockercompose.up /tmp/toto
# salt-call -l debug dockercompose.restart /tmp/toto '[database]'
# salt-call -l debug dockercompose.stop /tmp/toto
# salt-call -l debug dockercompose.rm /tmp/toto
Docker-compose method supported
-------------------------------
- up
- restart
- stop
- start
- pause
- unpause
- kill
- rm
- ps
- pull
- build
Functions
---------
- docker-compose.yml management
- :py:func:`dockercompose.create <salt.modules.dockercompose.create>`
- :py:func:`dockercompose.get <salt.modules.dockercompose.get>`
- Manage containers
- :py:func:`dockercompose.restart <salt.modules.dockercompose.restart>`
- :py:func:`dockercompose.stop <salt.modules.dockercompose.stop>`
- :py:func:`dockercompose.pause <salt.modules.dockercompose.pause>`
- :py:func:`dockercompose.unpause <salt.modules.dockercompose.unpause>`
- :py:func:`dockercompose.start <salt.modules.dockercompose.start>`
- :py:func:`dockercompose.kill <salt.modules.dockercompose.kill>`
- :py:func:`dockercompose.rm <salt.modules.dockercompose.rm>`
- :py:func:`dockercompose.up <salt.modules.dockercompose.up>`
- Manage containers image:
- :py:func:`dockercompose.pull <salt.modules.dockercompose.pull>`
- :py:func:`dockercompose.build <salt.modules.dockercompose.build>`
- Gather information about containers:
- :py:func:`dockercompose.ps <salt.modules.dockercompose.ps>`
- Manage service definitions:
- :py:func:`dockercompose.service_create <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_upsert <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_remove <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_set_tag <salt.modules.dockercompose.ps>`
Detailed Function Documentation
-------------------------------
'''
from __future__ import absolute_import, print_function, unicode_literals
import inspect
import logging
import os
import re
import salt.utils.files
import salt.utils.stringutils
from salt.ext import six
from operator import attrgetter
from salt.serializers import json
from salt.utils import yaml
try:
import compose
from compose.cli.command import get_project
from compose.service import ConvergenceStrategy
HAS_DOCKERCOMPOSE = True
except ImportError:
HAS_DOCKERCOMPOSE = False
try:
from compose.project import OneOffFilter
USE_FILTERCLASS = True
except ImportError:
USE_FILTERCLASS = False
MIN_DOCKERCOMPOSE = (1, 5, 0)
VERSION_RE = r'([\d.]+)'
log = logging.getLogger(__name__)
debug = False
__virtualname__ = 'dockercompose'
DEFAULT_DC_FILENAMES = ('docker-compose.yml', 'docker-compose.yaml')
def __virtual__():
if HAS_DOCKERCOMPOSE:
match = re.match(VERSION_RE, six.text_type(compose.__version__))
if match:
version = tuple([int(x) for x in match.group(1).split('.')])
if version >= MIN_DOCKERCOMPOSE:
return __virtualname__
return (False, 'The dockercompose execution module not loaded: '
'compose python library not available.')
def __standardize_result(status, message, data=None, debug_msg=None):
'''
Standardizes all responses
:param status:
:param message:
:param data:
:param debug_msg:
:return:
'''
result = {
'status': status,
'message': message
}
if data is not None:
result['return'] = data
if debug_msg is not None and debug:
result['debug'] = debug_msg
return result
def __get_docker_file_path(path):
'''
Determines the filepath to use
:param path:
:return:
'''
if os.path.isfile(path):
return path
for dc_filename in DEFAULT_DC_FILENAMES:
file_path = os.path.join(path, dc_filename)
if os.path.isfile(file_path):
return file_path
# implicitly return None
def __read_docker_compose_file(file_path):
'''
Read the compose file if it exists in the directory
:param file_path:
:return:
'''
if not os.path.isfile(file_path):
return __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
file_name = os.path.basename(file_path)
result = {file_name: ''}
for line in fl:
result[file_name] += salt.utils.stringutils.to_unicode(line)
except EnvironmentError:
return __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
return __standardize_result(True,
'Reading content of {0}'.format(file_path),
result, None)
def __load_docker_compose(path):
'''
Read the compose file and load its' contents
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return None, __standardize_result(False, msg,
None, None)
if not os.path.isfile(file_path):
return None, __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
loaded = yaml.load(fl)
except EnvironmentError:
return None, __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(file_path, yerr)
return None, __standardize_result(False, msg,
None, None)
if not loaded:
msg = 'Got empty compose file at {0}'.format(file_path)
return None, __standardize_result(False, msg,
None, None)
if 'services' not in loaded:
loaded['services'] = {}
result = {
'compose_content': loaded,
'file_name': os.path.basename(file_path)
}
return result, None
def __dump_docker_compose(path, content, already_existed):
'''
Dumps
:param path:
:param content: the not-yet dumped content
:return:
'''
try:
dumped = yaml.safe_dump(content, indent=2, default_flow_style=False)
return __write_docker_compose(path, dumped, already_existed)
except TypeError as t_err:
msg = 'Could not dump {0} {1}'.format(content, t_err)
return __standardize_result(False, msg,
None, None)
def __write_docker_compose(path, docker_compose, already_existed):
'''
Write docker-compose to a path
in order to use it with docker-compose ( config check )
:param path:
docker_compose
contains the docker-compose file
:return:
'''
if path.lower().endswith(('.yml', '.yaml')):
file_path = path
dir_name = os.path.dirname(path)
else:
dir_name = path
file_path = os.path.join(dir_name, DEFAULT_DC_FILENAMES[0])
if os.path.isdir(dir_name) is False:
os.mkdir(dir_name)
try:
with salt.utils.files.fopen(file_path, 'w') as fl:
fl.write(salt.utils.stringutils.to_str(docker_compose))
except EnvironmentError:
return __standardize_result(False,
'Could not write {0}'.format(file_path),
None, None)
project = __load_project_from_file_path(file_path)
if isinstance(project, dict):
if not already_existed:
os.remove(file_path)
return project
return file_path
def __load_project(path):
'''
Load a docker-compose project from path
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return __standardize_result(False,
msg,
None, None)
return __load_project_from_file_path(file_path)
def __load_project_from_file_path(file_path):
'''
Load a docker-compose project from file path
:param path:
:return:
'''
try:
project = get_project(project_dir=os.path.dirname(file_path),
config_path=[os.path.basename(file_path)])
except Exception as inst:
return __handle_except(inst)
return project
def __load_compose_definitions(path, definition):
'''
Will load the compose file located at path
Then determines the format/contents of the sent definition
err or results are only set if there were any
:param path:
:param definition:
:return tuple(compose_result, loaded_definition, err):
'''
compose_result, err = __load_docker_compose(path)
if err:
return None, None, err
if isinstance(definition, dict):
return compose_result, definition, None
elif definition.strip().startswith('{'):
try:
loaded_definition = json.deserialize(definition)
except json.DeserializationError as jerr:
msg = 'Could not parse {0} {1}'.format(definition, jerr)
return None, None, __standardize_result(False, msg,
None, None)
else:
try:
loaded_definition = yaml.load(definition)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(definition, yerr)
return None, None, __standardize_result(False, msg,
None, None)
return compose_result, loaded_definition, None
def __dump_compose_file(path, compose_result, success_msg, already_existed):
'''
Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return:
'''
ret = __dump_docker_compose(path,
compose_result['compose_content'],
already_existed)
if isinstance(ret, dict):
return ret
return __standardize_result(True, success_msg,
compose_result['compose_content'], None)
def __handle_except(inst):
'''
Handle exception and return a standard result
:param inst:
:return:
'''
return __standardize_result(False,
'Docker-compose command {0} failed'.
format(inspect.stack()[1][3]),
'{0}'.format(inst), None)
def _get_convergence_plans(project, service_names):
'''
Get action executed for each container
:param project:
:param service_names:
:return:
'''
ret = {}
plans = project._get_convergence_plans(project.get_services(service_names),
ConvergenceStrategy.changed)
for cont in plans:
(action, container) = plans[cont]
if action == 'create':
ret[cont] = 'Creating container'
elif action == 'recreate':
ret[cont] = 'Re-creating container'
elif action == 'start':
ret[cont] = 'Starting container'
elif action == 'noop':
ret[cont] = 'Container is up to date'
return ret
def get(path):
'''
Get the content of the docker-compose file into a directory
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.get /path/where/docker-compose/stored
'''
file_path = __get_docker_file_path(path)
if file_path is None:
return __standardize_result(False,
'Path {} is not present'.format(path),
None, None)
salt_result = __read_docker_compose_file(file_path)
if not salt_result['status']:
return salt_result
project = __load_project(path)
if isinstance(project, dict):
salt_result['return']['valid'] = False
else:
salt_result['return']['valid'] = True
return salt_result
def create(path, docker_compose):
'''
Create and validate a docker-compose file into a directory
path
Path where the docker-compose file will be stored on the server
docker_compose
docker_compose file
CLI Example:
.. code-block:: bash
salt myminion dockercompose.create /path/where/docker-compose/stored content
'''
if docker_compose:
ret = __write_docker_compose(path,
docker_compose,
already_existed=False)
if isinstance(ret, dict):
return ret
else:
return __standardize_result(False,
'Creating a docker-compose project failed, you must send a valid docker-compose file',
None, None)
return __standardize_result(True,
'Successfully created the docker-compose file',
{'compose.base_dir': path},
None)
def pull(path, service_names=None):
'''
Pull image for containers in the docker-compose file, service_names is a
python list, if omitted pull all images
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pull /path/where/docker-compose/stored
salt myminion dockercompose.pull /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.pull(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pulling containers images via docker-compose succeeded',
None, None)
def build(path, service_names=None):
'''
Build image for containers in the docker-compose file, service_names is a
python list, if omitted build images for all containers. Please note
that at the moment the module does not allow you to upload your Dockerfile,
nor any other file you could need with your docker-compose.yml, you will
have to make sure the files you need are actually in the directory specified
in the `build` keyword
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.build /path/where/docker-compose/stored
salt myminion dockercompose.build /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.build(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Building containers images via docker-compose succeeded',
None, None)
def restart(path, service_names=None):
'''
Restart container(s) in the docker-compose file, service_names is a python
list, if omitted restart all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will restart only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.restart /path/where/docker-compose/stored
salt myminion dockercompose.restart /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.restart(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'restarted'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Restarting containers via docker-compose', result, debug_ret)
def stop(path, service_names=None):
'''
Stop running containers in the docker-compose file, service_names is a python
list, if omitted stop all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will stop only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.stop /path/where/docker-compose/stored
salt myminion dockercompose.stop /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
def unpause(path, service_names=None):
'''
Un-Pause containers in the docker-compose file, service_names is a python
list, if omitted unpause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will un-pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.unpause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'unpaused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Un-Pausing containers via docker-compose', result, debug_ret)
def start(path, service_names=None):
'''
Start containers in the docker-compose file, service_names is a python
list, if omitted start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.start /path/where/docker-compose/stored
salt myminion dockercompose.start /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.start(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'started'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Starting containers via docker-compose', result, debug_ret)
def kill(path, service_names=None):
'''
Kill containers in the docker-compose file, service_names is a python
list, if omitted kill all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will kill only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.kill /path/where/docker-compose/stored
salt myminion dockercompose.kill /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.kill(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'killed'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Killing containers via docker-compose', result, debug_ret)
def rm(path, service_names=None):
'''
Remove stopped containers in the docker-compose file, service_names is a python
list, if omitted remove all stopped containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will remove only the specified stopped services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.rm /path/where/docker-compose/stored
salt myminion dockercompose.rm /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.remove_stopped(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Removing stopped containers via docker-compose', None, None)
def ps(path):
'''
List all running containers and report some information about them
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.ps /path/where/docker-compose/stored
'''
project = __load_project(path)
result = {}
if isinstance(project, dict):
return project
else:
if USE_FILTERCLASS:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, OneOffFilter.only),
key=attrgetter('name'))
else:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, one_off=True),
key=attrgetter('name'))
for container in containers:
command = container.human_readable_command
if len(command) > 30:
command = '{0} ...'.format(command[:26])
result[container.name] = {
'id': container.id,
'name': container.name,
'command': command,
'state': container.human_readable_state,
'ports': container.human_readable_ports,
}
return __standardize_result(True, 'Listing docker-compose containers', result, None)
def up(path, service_names=None):
'''
Create and start containers defined in the docker-compose.yml file
located in path, service_names is a python list, if omitted create and
start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will create and start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.up /path/where/docker-compose/stored
salt myminion dockercompose.up /path/where/docker-compose/stored '[janus]'
'''
debug_ret = {}
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
result = _get_convergence_plans(project, service_names)
ret = project.up(service_names)
if debug:
for container in ret:
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Adding containers via docker-compose', result, debug_ret)
def service_create(path, service_name, definition):
'''
Create the definition of a docker-compose service
This fails when the service already exists
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service {0} created'.format(service_name),
already_existed=True)
def service_upsert(path, service_name, definition):
'''
Create or update the definition of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_upsert /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service definition for {0} is set'.format(service_name),
already_existed=True)
def service_remove(path, service_name):
'''
Remove the definition of a docker-compose service
This does not rm the container
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_remove /path/where/docker-compose/stored service_name
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
del services[service_name]
return __dump_compose_file(path, compose_result,
'Service {0} is removed from {1}'.format(service_name, path),
already_existed=True)
def service_set_tag(path, service_name, tag):
'''
Change the tag of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
tag
Name of the tag (often used as version) that the service image should have
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name tag
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
if 'image' not in services[service_name]:
return __standardize_result(False,
'Service {0} did not contain the variable "image"'.format(service_name),
None, None)
image = services[service_name]['image'].split(':')[0]
services[service_name]['image'] = '{0}:{1}'.format(image, tag)
return __dump_compose_file(path, compose_result,
'Service {0} is set to tag "{1}"'.format(service_name, tag),
already_existed=True)
|
saltstack/salt
|
salt/modules/dockercompose.py
|
rm
|
python
|
def rm(path, service_names=None):
'''
Remove stopped containers in the docker-compose file, service_names is a python
list, if omitted remove all stopped containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will remove only the specified stopped services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.rm /path/where/docker-compose/stored
salt myminion dockercompose.rm /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.remove_stopped(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Removing stopped containers via docker-compose', None, None)
|
Remove stopped containers in the docker-compose file, service_names is a python
list, if omitted remove all stopped containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will remove only the specified stopped services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.rm /path/where/docker-compose/stored
salt myminion dockercompose.rm /path/where/docker-compose/stored '[janus]'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockercompose.py#L785-L811
|
[
"def __standardize_result(status, message, data=None, debug_msg=None):\n '''\n Standardizes all responses\n\n :param status:\n :param message:\n :param data:\n :param debug_msg:\n :return:\n '''\n result = {\n 'status': status,\n 'message': message\n }\n\n if data is not None:\n result['return'] = data\n\n if debug_msg is not None and debug:\n result['debug'] = debug_msg\n\n return result\n",
"def __load_project(path):\n '''\n Load a docker-compose project from path\n\n :param path:\n :return:\n '''\n file_path = __get_docker_file_path(path)\n if file_path is None:\n msg = 'Could not find docker-compose file at {0}'.format(path)\n return __standardize_result(False,\n msg,\n None, None)\n return __load_project_from_file_path(file_path)\n",
"def __handle_except(inst):\n '''\n Handle exception and return a standard result\n\n :param inst:\n :return:\n '''\n return __standardize_result(False,\n 'Docker-compose command {0} failed'.\n format(inspect.stack()[1][3]),\n '{0}'.format(inst), None)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to import docker-compose via saltstack
.. versionadded:: 2016.3.0
:maintainer: Jean Praloran <jeanpralo@gmail.com>
:maturity: new
:depends: docker-compose>=1.5
:platform: all
Introduction
------------
This module allows one to deal with docker-compose file in a directory.
This is a first version only, the following commands are missing at the moment
but will be built later on if the community is interested in this module:
- run
- logs
- port
- scale
Installation Prerequisites
--------------------------
This execution module requires at least version 1.4.0 of both docker-compose_ and
Docker_. docker-compose can easily be installed using :py:func:`pip.install
<salt.modules.pip.install>`:
.. code-block:: bash
salt myminion pip.install docker-compose>=1.5.0
.. _docker-compose: https://pypi.python.org/pypi/docker-compose
.. _Docker: https://www.docker.com/
How to use this module?
-----------------------
In order to use the module if you have no docker-compose file on the server you
can issue the command create, it takes two arguments the path where the
docker-compose.yml will be stored and the content of this latter:
.. code-block:: text
# salt-call -l debug dockercompose.create /tmp/toto '
database:
image: mongo:3.0
command: mongod --smallfiles --quiet --logpath=/dev/null
'
Then you can execute a list of method defined at the bottom with at least one
argument (the path where the docker-compose.yml will be read) and an optional
python list which corresponds to the services names:
.. code-block:: bash
# salt-call -l debug dockercompose.up /tmp/toto
# salt-call -l debug dockercompose.restart /tmp/toto '[database]'
# salt-call -l debug dockercompose.stop /tmp/toto
# salt-call -l debug dockercompose.rm /tmp/toto
Docker-compose method supported
-------------------------------
- up
- restart
- stop
- start
- pause
- unpause
- kill
- rm
- ps
- pull
- build
Functions
---------
- docker-compose.yml management
- :py:func:`dockercompose.create <salt.modules.dockercompose.create>`
- :py:func:`dockercompose.get <salt.modules.dockercompose.get>`
- Manage containers
- :py:func:`dockercompose.restart <salt.modules.dockercompose.restart>`
- :py:func:`dockercompose.stop <salt.modules.dockercompose.stop>`
- :py:func:`dockercompose.pause <salt.modules.dockercompose.pause>`
- :py:func:`dockercompose.unpause <salt.modules.dockercompose.unpause>`
- :py:func:`dockercompose.start <salt.modules.dockercompose.start>`
- :py:func:`dockercompose.kill <salt.modules.dockercompose.kill>`
- :py:func:`dockercompose.rm <salt.modules.dockercompose.rm>`
- :py:func:`dockercompose.up <salt.modules.dockercompose.up>`
- Manage containers image:
- :py:func:`dockercompose.pull <salt.modules.dockercompose.pull>`
- :py:func:`dockercompose.build <salt.modules.dockercompose.build>`
- Gather information about containers:
- :py:func:`dockercompose.ps <salt.modules.dockercompose.ps>`
- Manage service definitions:
- :py:func:`dockercompose.service_create <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_upsert <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_remove <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_set_tag <salt.modules.dockercompose.ps>`
Detailed Function Documentation
-------------------------------
'''
from __future__ import absolute_import, print_function, unicode_literals
import inspect
import logging
import os
import re
import salt.utils.files
import salt.utils.stringutils
from salt.ext import six
from operator import attrgetter
from salt.serializers import json
from salt.utils import yaml
try:
import compose
from compose.cli.command import get_project
from compose.service import ConvergenceStrategy
HAS_DOCKERCOMPOSE = True
except ImportError:
HAS_DOCKERCOMPOSE = False
try:
from compose.project import OneOffFilter
USE_FILTERCLASS = True
except ImportError:
USE_FILTERCLASS = False
MIN_DOCKERCOMPOSE = (1, 5, 0)
VERSION_RE = r'([\d.]+)'
log = logging.getLogger(__name__)
debug = False
__virtualname__ = 'dockercompose'
DEFAULT_DC_FILENAMES = ('docker-compose.yml', 'docker-compose.yaml')
def __virtual__():
if HAS_DOCKERCOMPOSE:
match = re.match(VERSION_RE, six.text_type(compose.__version__))
if match:
version = tuple([int(x) for x in match.group(1).split('.')])
if version >= MIN_DOCKERCOMPOSE:
return __virtualname__
return (False, 'The dockercompose execution module not loaded: '
'compose python library not available.')
def __standardize_result(status, message, data=None, debug_msg=None):
'''
Standardizes all responses
:param status:
:param message:
:param data:
:param debug_msg:
:return:
'''
result = {
'status': status,
'message': message
}
if data is not None:
result['return'] = data
if debug_msg is not None and debug:
result['debug'] = debug_msg
return result
def __get_docker_file_path(path):
'''
Determines the filepath to use
:param path:
:return:
'''
if os.path.isfile(path):
return path
for dc_filename in DEFAULT_DC_FILENAMES:
file_path = os.path.join(path, dc_filename)
if os.path.isfile(file_path):
return file_path
# implicitly return None
def __read_docker_compose_file(file_path):
'''
Read the compose file if it exists in the directory
:param file_path:
:return:
'''
if not os.path.isfile(file_path):
return __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
file_name = os.path.basename(file_path)
result = {file_name: ''}
for line in fl:
result[file_name] += salt.utils.stringutils.to_unicode(line)
except EnvironmentError:
return __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
return __standardize_result(True,
'Reading content of {0}'.format(file_path),
result, None)
def __load_docker_compose(path):
'''
Read the compose file and load its' contents
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return None, __standardize_result(False, msg,
None, None)
if not os.path.isfile(file_path):
return None, __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
loaded = yaml.load(fl)
except EnvironmentError:
return None, __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(file_path, yerr)
return None, __standardize_result(False, msg,
None, None)
if not loaded:
msg = 'Got empty compose file at {0}'.format(file_path)
return None, __standardize_result(False, msg,
None, None)
if 'services' not in loaded:
loaded['services'] = {}
result = {
'compose_content': loaded,
'file_name': os.path.basename(file_path)
}
return result, None
def __dump_docker_compose(path, content, already_existed):
'''
Dumps
:param path:
:param content: the not-yet dumped content
:return:
'''
try:
dumped = yaml.safe_dump(content, indent=2, default_flow_style=False)
return __write_docker_compose(path, dumped, already_existed)
except TypeError as t_err:
msg = 'Could not dump {0} {1}'.format(content, t_err)
return __standardize_result(False, msg,
None, None)
def __write_docker_compose(path, docker_compose, already_existed):
'''
Write docker-compose to a path
in order to use it with docker-compose ( config check )
:param path:
docker_compose
contains the docker-compose file
:return:
'''
if path.lower().endswith(('.yml', '.yaml')):
file_path = path
dir_name = os.path.dirname(path)
else:
dir_name = path
file_path = os.path.join(dir_name, DEFAULT_DC_FILENAMES[0])
if os.path.isdir(dir_name) is False:
os.mkdir(dir_name)
try:
with salt.utils.files.fopen(file_path, 'w') as fl:
fl.write(salt.utils.stringutils.to_str(docker_compose))
except EnvironmentError:
return __standardize_result(False,
'Could not write {0}'.format(file_path),
None, None)
project = __load_project_from_file_path(file_path)
if isinstance(project, dict):
if not already_existed:
os.remove(file_path)
return project
return file_path
def __load_project(path):
'''
Load a docker-compose project from path
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return __standardize_result(False,
msg,
None, None)
return __load_project_from_file_path(file_path)
def __load_project_from_file_path(file_path):
'''
Load a docker-compose project from file path
:param path:
:return:
'''
try:
project = get_project(project_dir=os.path.dirname(file_path),
config_path=[os.path.basename(file_path)])
except Exception as inst:
return __handle_except(inst)
return project
def __load_compose_definitions(path, definition):
'''
Will load the compose file located at path
Then determines the format/contents of the sent definition
err or results are only set if there were any
:param path:
:param definition:
:return tuple(compose_result, loaded_definition, err):
'''
compose_result, err = __load_docker_compose(path)
if err:
return None, None, err
if isinstance(definition, dict):
return compose_result, definition, None
elif definition.strip().startswith('{'):
try:
loaded_definition = json.deserialize(definition)
except json.DeserializationError as jerr:
msg = 'Could not parse {0} {1}'.format(definition, jerr)
return None, None, __standardize_result(False, msg,
None, None)
else:
try:
loaded_definition = yaml.load(definition)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(definition, yerr)
return None, None, __standardize_result(False, msg,
None, None)
return compose_result, loaded_definition, None
def __dump_compose_file(path, compose_result, success_msg, already_existed):
'''
Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return:
'''
ret = __dump_docker_compose(path,
compose_result['compose_content'],
already_existed)
if isinstance(ret, dict):
return ret
return __standardize_result(True, success_msg,
compose_result['compose_content'], None)
def __handle_except(inst):
'''
Handle exception and return a standard result
:param inst:
:return:
'''
return __standardize_result(False,
'Docker-compose command {0} failed'.
format(inspect.stack()[1][3]),
'{0}'.format(inst), None)
def _get_convergence_plans(project, service_names):
'''
Get action executed for each container
:param project:
:param service_names:
:return:
'''
ret = {}
plans = project._get_convergence_plans(project.get_services(service_names),
ConvergenceStrategy.changed)
for cont in plans:
(action, container) = plans[cont]
if action == 'create':
ret[cont] = 'Creating container'
elif action == 'recreate':
ret[cont] = 'Re-creating container'
elif action == 'start':
ret[cont] = 'Starting container'
elif action == 'noop':
ret[cont] = 'Container is up to date'
return ret
def get(path):
'''
Get the content of the docker-compose file into a directory
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.get /path/where/docker-compose/stored
'''
file_path = __get_docker_file_path(path)
if file_path is None:
return __standardize_result(False,
'Path {} is not present'.format(path),
None, None)
salt_result = __read_docker_compose_file(file_path)
if not salt_result['status']:
return salt_result
project = __load_project(path)
if isinstance(project, dict):
salt_result['return']['valid'] = False
else:
salt_result['return']['valid'] = True
return salt_result
def create(path, docker_compose):
'''
Create and validate a docker-compose file into a directory
path
Path where the docker-compose file will be stored on the server
docker_compose
docker_compose file
CLI Example:
.. code-block:: bash
salt myminion dockercompose.create /path/where/docker-compose/stored content
'''
if docker_compose:
ret = __write_docker_compose(path,
docker_compose,
already_existed=False)
if isinstance(ret, dict):
return ret
else:
return __standardize_result(False,
'Creating a docker-compose project failed, you must send a valid docker-compose file',
None, None)
return __standardize_result(True,
'Successfully created the docker-compose file',
{'compose.base_dir': path},
None)
def pull(path, service_names=None):
'''
Pull image for containers in the docker-compose file, service_names is a
python list, if omitted pull all images
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pull /path/where/docker-compose/stored
salt myminion dockercompose.pull /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.pull(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pulling containers images via docker-compose succeeded',
None, None)
def build(path, service_names=None):
'''
Build image for containers in the docker-compose file, service_names is a
python list, if omitted build images for all containers. Please note
that at the moment the module does not allow you to upload your Dockerfile,
nor any other file you could need with your docker-compose.yml, you will
have to make sure the files you need are actually in the directory specified
in the `build` keyword
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.build /path/where/docker-compose/stored
salt myminion dockercompose.build /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.build(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Building containers images via docker-compose succeeded',
None, None)
def restart(path, service_names=None):
'''
Restart container(s) in the docker-compose file, service_names is a python
list, if omitted restart all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will restart only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.restart /path/where/docker-compose/stored
salt myminion dockercompose.restart /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.restart(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'restarted'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Restarting containers via docker-compose', result, debug_ret)
def stop(path, service_names=None):
'''
Stop running containers in the docker-compose file, service_names is a python
list, if omitted stop all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will stop only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.stop /path/where/docker-compose/stored
salt myminion dockercompose.stop /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
def pause(path, service_names=None):
'''
Pause running containers in the docker-compose file, service_names is a python
list, if omitted pause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.pause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'paused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pausing containers via docker-compose', result, debug_ret)
def unpause(path, service_names=None):
'''
Un-Pause containers in the docker-compose file, service_names is a python
list, if omitted unpause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will un-pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.unpause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'unpaused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Un-Pausing containers via docker-compose', result, debug_ret)
def start(path, service_names=None):
'''
Start containers in the docker-compose file, service_names is a python
list, if omitted start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.start /path/where/docker-compose/stored
salt myminion dockercompose.start /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.start(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'started'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Starting containers via docker-compose', result, debug_ret)
def kill(path, service_names=None):
'''
Kill containers in the docker-compose file, service_names is a python
list, if omitted kill all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will kill only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.kill /path/where/docker-compose/stored
salt myminion dockercompose.kill /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.kill(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'killed'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Killing containers via docker-compose', result, debug_ret)
def ps(path):
'''
List all running containers and report some information about them
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.ps /path/where/docker-compose/stored
'''
project = __load_project(path)
result = {}
if isinstance(project, dict):
return project
else:
if USE_FILTERCLASS:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, OneOffFilter.only),
key=attrgetter('name'))
else:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, one_off=True),
key=attrgetter('name'))
for container in containers:
command = container.human_readable_command
if len(command) > 30:
command = '{0} ...'.format(command[:26])
result[container.name] = {
'id': container.id,
'name': container.name,
'command': command,
'state': container.human_readable_state,
'ports': container.human_readable_ports,
}
return __standardize_result(True, 'Listing docker-compose containers', result, None)
def up(path, service_names=None):
'''
Create and start containers defined in the docker-compose.yml file
located in path, service_names is a python list, if omitted create and
start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will create and start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.up /path/where/docker-compose/stored
salt myminion dockercompose.up /path/where/docker-compose/stored '[janus]'
'''
debug_ret = {}
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
result = _get_convergence_plans(project, service_names)
ret = project.up(service_names)
if debug:
for container in ret:
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Adding containers via docker-compose', result, debug_ret)
def service_create(path, service_name, definition):
'''
Create the definition of a docker-compose service
This fails when the service already exists
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service {0} created'.format(service_name),
already_existed=True)
def service_upsert(path, service_name, definition):
'''
Create or update the definition of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_upsert /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service definition for {0} is set'.format(service_name),
already_existed=True)
def service_remove(path, service_name):
'''
Remove the definition of a docker-compose service
This does not rm the container
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_remove /path/where/docker-compose/stored service_name
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
del services[service_name]
return __dump_compose_file(path, compose_result,
'Service {0} is removed from {1}'.format(service_name, path),
already_existed=True)
def service_set_tag(path, service_name, tag):
'''
Change the tag of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
tag
Name of the tag (often used as version) that the service image should have
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name tag
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
if 'image' not in services[service_name]:
return __standardize_result(False,
'Service {0} did not contain the variable "image"'.format(service_name),
None, None)
image = services[service_name]['image'].split(':')[0]
services[service_name]['image'] = '{0}:{1}'.format(image, tag)
return __dump_compose_file(path, compose_result,
'Service {0} is set to tag "{1}"'.format(service_name, tag),
already_existed=True)
|
saltstack/salt
|
salt/modules/dockercompose.py
|
ps
|
python
|
def ps(path):
'''
List all running containers and report some information about them
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.ps /path/where/docker-compose/stored
'''
project = __load_project(path)
result = {}
if isinstance(project, dict):
return project
else:
if USE_FILTERCLASS:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, OneOffFilter.only),
key=attrgetter('name'))
else:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, one_off=True),
key=attrgetter('name'))
for container in containers:
command = container.human_readable_command
if len(command) > 30:
command = '{0} ...'.format(command[:26])
result[container.name] = {
'id': container.id,
'name': container.name,
'command': command,
'state': container.human_readable_state,
'ports': container.human_readable_ports,
}
return __standardize_result(True, 'Listing docker-compose containers', result, None)
|
List all running containers and report some information about them
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.ps /path/where/docker-compose/stored
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockercompose.py#L814-L854
|
[
"def __standardize_result(status, message, data=None, debug_msg=None):\n '''\n Standardizes all responses\n\n :param status:\n :param message:\n :param data:\n :param debug_msg:\n :return:\n '''\n result = {\n 'status': status,\n 'message': message\n }\n\n if data is not None:\n result['return'] = data\n\n if debug_msg is not None and debug:\n result['debug'] = debug_msg\n\n return result\n",
"def __load_project(path):\n '''\n Load a docker-compose project from path\n\n :param path:\n :return:\n '''\n file_path = __get_docker_file_path(path)\n if file_path is None:\n msg = 'Could not find docker-compose file at {0}'.format(path)\n return __standardize_result(False,\n msg,\n None, None)\n return __load_project_from_file_path(file_path)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to import docker-compose via saltstack
.. versionadded:: 2016.3.0
:maintainer: Jean Praloran <jeanpralo@gmail.com>
:maturity: new
:depends: docker-compose>=1.5
:platform: all
Introduction
------------
This module allows one to deal with docker-compose file in a directory.
This is a first version only, the following commands are missing at the moment
but will be built later on if the community is interested in this module:
- run
- logs
- port
- scale
Installation Prerequisites
--------------------------
This execution module requires at least version 1.4.0 of both docker-compose_ and
Docker_. docker-compose can easily be installed using :py:func:`pip.install
<salt.modules.pip.install>`:
.. code-block:: bash
salt myminion pip.install docker-compose>=1.5.0
.. _docker-compose: https://pypi.python.org/pypi/docker-compose
.. _Docker: https://www.docker.com/
How to use this module?
-----------------------
In order to use the module if you have no docker-compose file on the server you
can issue the command create, it takes two arguments the path where the
docker-compose.yml will be stored and the content of this latter:
.. code-block:: text
# salt-call -l debug dockercompose.create /tmp/toto '
database:
image: mongo:3.0
command: mongod --smallfiles --quiet --logpath=/dev/null
'
Then you can execute a list of method defined at the bottom with at least one
argument (the path where the docker-compose.yml will be read) and an optional
python list which corresponds to the services names:
.. code-block:: bash
# salt-call -l debug dockercompose.up /tmp/toto
# salt-call -l debug dockercompose.restart /tmp/toto '[database]'
# salt-call -l debug dockercompose.stop /tmp/toto
# salt-call -l debug dockercompose.rm /tmp/toto
Docker-compose method supported
-------------------------------
- up
- restart
- stop
- start
- pause
- unpause
- kill
- rm
- ps
- pull
- build
Functions
---------
- docker-compose.yml management
- :py:func:`dockercompose.create <salt.modules.dockercompose.create>`
- :py:func:`dockercompose.get <salt.modules.dockercompose.get>`
- Manage containers
- :py:func:`dockercompose.restart <salt.modules.dockercompose.restart>`
- :py:func:`dockercompose.stop <salt.modules.dockercompose.stop>`
- :py:func:`dockercompose.pause <salt.modules.dockercompose.pause>`
- :py:func:`dockercompose.unpause <salt.modules.dockercompose.unpause>`
- :py:func:`dockercompose.start <salt.modules.dockercompose.start>`
- :py:func:`dockercompose.kill <salt.modules.dockercompose.kill>`
- :py:func:`dockercompose.rm <salt.modules.dockercompose.rm>`
- :py:func:`dockercompose.up <salt.modules.dockercompose.up>`
- Manage containers image:
- :py:func:`dockercompose.pull <salt.modules.dockercompose.pull>`
- :py:func:`dockercompose.build <salt.modules.dockercompose.build>`
- Gather information about containers:
- :py:func:`dockercompose.ps <salt.modules.dockercompose.ps>`
- Manage service definitions:
- :py:func:`dockercompose.service_create <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_upsert <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_remove <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_set_tag <salt.modules.dockercompose.ps>`
Detailed Function Documentation
-------------------------------
'''
from __future__ import absolute_import, print_function, unicode_literals
import inspect
import logging
import os
import re
import salt.utils.files
import salt.utils.stringutils
from salt.ext import six
from operator import attrgetter
from salt.serializers import json
from salt.utils import yaml
try:
import compose
from compose.cli.command import get_project
from compose.service import ConvergenceStrategy
HAS_DOCKERCOMPOSE = True
except ImportError:
HAS_DOCKERCOMPOSE = False
try:
from compose.project import OneOffFilter
USE_FILTERCLASS = True
except ImportError:
USE_FILTERCLASS = False
MIN_DOCKERCOMPOSE = (1, 5, 0)
VERSION_RE = r'([\d.]+)'
log = logging.getLogger(__name__)
debug = False
__virtualname__ = 'dockercompose'
DEFAULT_DC_FILENAMES = ('docker-compose.yml', 'docker-compose.yaml')
def __virtual__():
if HAS_DOCKERCOMPOSE:
match = re.match(VERSION_RE, six.text_type(compose.__version__))
if match:
version = tuple([int(x) for x in match.group(1).split('.')])
if version >= MIN_DOCKERCOMPOSE:
return __virtualname__
return (False, 'The dockercompose execution module not loaded: '
'compose python library not available.')
def __standardize_result(status, message, data=None, debug_msg=None):
'''
Standardizes all responses
:param status:
:param message:
:param data:
:param debug_msg:
:return:
'''
result = {
'status': status,
'message': message
}
if data is not None:
result['return'] = data
if debug_msg is not None and debug:
result['debug'] = debug_msg
return result
def __get_docker_file_path(path):
'''
Determines the filepath to use
:param path:
:return:
'''
if os.path.isfile(path):
return path
for dc_filename in DEFAULT_DC_FILENAMES:
file_path = os.path.join(path, dc_filename)
if os.path.isfile(file_path):
return file_path
# implicitly return None
def __read_docker_compose_file(file_path):
'''
Read the compose file if it exists in the directory
:param file_path:
:return:
'''
if not os.path.isfile(file_path):
return __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
file_name = os.path.basename(file_path)
result = {file_name: ''}
for line in fl:
result[file_name] += salt.utils.stringutils.to_unicode(line)
except EnvironmentError:
return __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
return __standardize_result(True,
'Reading content of {0}'.format(file_path),
result, None)
def __load_docker_compose(path):
'''
Read the compose file and load its' contents
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return None, __standardize_result(False, msg,
None, None)
if not os.path.isfile(file_path):
return None, __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
loaded = yaml.load(fl)
except EnvironmentError:
return None, __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(file_path, yerr)
return None, __standardize_result(False, msg,
None, None)
if not loaded:
msg = 'Got empty compose file at {0}'.format(file_path)
return None, __standardize_result(False, msg,
None, None)
if 'services' not in loaded:
loaded['services'] = {}
result = {
'compose_content': loaded,
'file_name': os.path.basename(file_path)
}
return result, None
def __dump_docker_compose(path, content, already_existed):
'''
Dumps
:param path:
:param content: the not-yet dumped content
:return:
'''
try:
dumped = yaml.safe_dump(content, indent=2, default_flow_style=False)
return __write_docker_compose(path, dumped, already_existed)
except TypeError as t_err:
msg = 'Could not dump {0} {1}'.format(content, t_err)
return __standardize_result(False, msg,
None, None)
def __write_docker_compose(path, docker_compose, already_existed):
'''
Write docker-compose to a path
in order to use it with docker-compose ( config check )
:param path:
docker_compose
contains the docker-compose file
:return:
'''
if path.lower().endswith(('.yml', '.yaml')):
file_path = path
dir_name = os.path.dirname(path)
else:
dir_name = path
file_path = os.path.join(dir_name, DEFAULT_DC_FILENAMES[0])
if os.path.isdir(dir_name) is False:
os.mkdir(dir_name)
try:
with salt.utils.files.fopen(file_path, 'w') as fl:
fl.write(salt.utils.stringutils.to_str(docker_compose))
except EnvironmentError:
return __standardize_result(False,
'Could not write {0}'.format(file_path),
None, None)
project = __load_project_from_file_path(file_path)
if isinstance(project, dict):
if not already_existed:
os.remove(file_path)
return project
return file_path
def __load_project(path):
'''
Load a docker-compose project from path
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return __standardize_result(False,
msg,
None, None)
return __load_project_from_file_path(file_path)
def __load_project_from_file_path(file_path):
'''
Load a docker-compose project from file path
:param path:
:return:
'''
try:
project = get_project(project_dir=os.path.dirname(file_path),
config_path=[os.path.basename(file_path)])
except Exception as inst:
return __handle_except(inst)
return project
def __load_compose_definitions(path, definition):
'''
Will load the compose file located at path
Then determines the format/contents of the sent definition
err or results are only set if there were any
:param path:
:param definition:
:return tuple(compose_result, loaded_definition, err):
'''
compose_result, err = __load_docker_compose(path)
if err:
return None, None, err
if isinstance(definition, dict):
return compose_result, definition, None
elif definition.strip().startswith('{'):
try:
loaded_definition = json.deserialize(definition)
except json.DeserializationError as jerr:
msg = 'Could not parse {0} {1}'.format(definition, jerr)
return None, None, __standardize_result(False, msg,
None, None)
else:
try:
loaded_definition = yaml.load(definition)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(definition, yerr)
return None, None, __standardize_result(False, msg,
None, None)
return compose_result, loaded_definition, None
def __dump_compose_file(path, compose_result, success_msg, already_existed):
'''
Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return:
'''
ret = __dump_docker_compose(path,
compose_result['compose_content'],
already_existed)
if isinstance(ret, dict):
return ret
return __standardize_result(True, success_msg,
compose_result['compose_content'], None)
def __handle_except(inst):
'''
Handle exception and return a standard result
:param inst:
:return:
'''
return __standardize_result(False,
'Docker-compose command {0} failed'.
format(inspect.stack()[1][3]),
'{0}'.format(inst), None)
def _get_convergence_plans(project, service_names):
'''
Get action executed for each container
:param project:
:param service_names:
:return:
'''
ret = {}
plans = project._get_convergence_plans(project.get_services(service_names),
ConvergenceStrategy.changed)
for cont in plans:
(action, container) = plans[cont]
if action == 'create':
ret[cont] = 'Creating container'
elif action == 'recreate':
ret[cont] = 'Re-creating container'
elif action == 'start':
ret[cont] = 'Starting container'
elif action == 'noop':
ret[cont] = 'Container is up to date'
return ret
def get(path):
'''
Get the content of the docker-compose file into a directory
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.get /path/where/docker-compose/stored
'''
file_path = __get_docker_file_path(path)
if file_path is None:
return __standardize_result(False,
'Path {} is not present'.format(path),
None, None)
salt_result = __read_docker_compose_file(file_path)
if not salt_result['status']:
return salt_result
project = __load_project(path)
if isinstance(project, dict):
salt_result['return']['valid'] = False
else:
salt_result['return']['valid'] = True
return salt_result
def create(path, docker_compose):
'''
Create and validate a docker-compose file into a directory
path
Path where the docker-compose file will be stored on the server
docker_compose
docker_compose file
CLI Example:
.. code-block:: bash
salt myminion dockercompose.create /path/where/docker-compose/stored content
'''
if docker_compose:
ret = __write_docker_compose(path,
docker_compose,
already_existed=False)
if isinstance(ret, dict):
return ret
else:
return __standardize_result(False,
'Creating a docker-compose project failed, you must send a valid docker-compose file',
None, None)
return __standardize_result(True,
'Successfully created the docker-compose file',
{'compose.base_dir': path},
None)
def pull(path, service_names=None):
'''
Pull image for containers in the docker-compose file, service_names is a
python list, if omitted pull all images
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pull /path/where/docker-compose/stored
salt myminion dockercompose.pull /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.pull(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pulling containers images via docker-compose succeeded',
None, None)
def build(path, service_names=None):
'''
Build image for containers in the docker-compose file, service_names is a
python list, if omitted build images for all containers. Please note
that at the moment the module does not allow you to upload your Dockerfile,
nor any other file you could need with your docker-compose.yml, you will
have to make sure the files you need are actually in the directory specified
in the `build` keyword
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.build /path/where/docker-compose/stored
salt myminion dockercompose.build /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.build(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Building containers images via docker-compose succeeded',
None, None)
def restart(path, service_names=None):
'''
Restart container(s) in the docker-compose file, service_names is a python
list, if omitted restart all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will restart only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.restart /path/where/docker-compose/stored
salt myminion dockercompose.restart /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.restart(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'restarted'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Restarting containers via docker-compose', result, debug_ret)
def stop(path, service_names=None):
'''
Stop running containers in the docker-compose file, service_names is a python
list, if omitted stop all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will stop only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.stop /path/where/docker-compose/stored
salt myminion dockercompose.stop /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
def pause(path, service_names=None):
'''
Pause running containers in the docker-compose file, service_names is a python
list, if omitted pause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.pause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'paused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pausing containers via docker-compose', result, debug_ret)
def unpause(path, service_names=None):
'''
Un-Pause containers in the docker-compose file, service_names is a python
list, if omitted unpause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will un-pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.unpause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'unpaused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Un-Pausing containers via docker-compose', result, debug_ret)
def start(path, service_names=None):
'''
Start containers in the docker-compose file, service_names is a python
list, if omitted start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.start /path/where/docker-compose/stored
salt myminion dockercompose.start /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.start(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'started'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Starting containers via docker-compose', result, debug_ret)
def kill(path, service_names=None):
'''
Kill containers in the docker-compose file, service_names is a python
list, if omitted kill all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will kill only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.kill /path/where/docker-compose/stored
salt myminion dockercompose.kill /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.kill(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'killed'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Killing containers via docker-compose', result, debug_ret)
def rm(path, service_names=None):
'''
Remove stopped containers in the docker-compose file, service_names is a python
list, if omitted remove all stopped containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will remove only the specified stopped services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.rm /path/where/docker-compose/stored
salt myminion dockercompose.rm /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.remove_stopped(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Removing stopped containers via docker-compose', None, None)
def up(path, service_names=None):
'''
Create and start containers defined in the docker-compose.yml file
located in path, service_names is a python list, if omitted create and
start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will create and start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.up /path/where/docker-compose/stored
salt myminion dockercompose.up /path/where/docker-compose/stored '[janus]'
'''
debug_ret = {}
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
result = _get_convergence_plans(project, service_names)
ret = project.up(service_names)
if debug:
for container in ret:
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Adding containers via docker-compose', result, debug_ret)
def service_create(path, service_name, definition):
'''
Create the definition of a docker-compose service
This fails when the service already exists
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service {0} created'.format(service_name),
already_existed=True)
def service_upsert(path, service_name, definition):
'''
Create or update the definition of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_upsert /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service definition for {0} is set'.format(service_name),
already_existed=True)
def service_remove(path, service_name):
'''
Remove the definition of a docker-compose service
This does not rm the container
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_remove /path/where/docker-compose/stored service_name
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
del services[service_name]
return __dump_compose_file(path, compose_result,
'Service {0} is removed from {1}'.format(service_name, path),
already_existed=True)
def service_set_tag(path, service_name, tag):
'''
Change the tag of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
tag
Name of the tag (often used as version) that the service image should have
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name tag
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
if 'image' not in services[service_name]:
return __standardize_result(False,
'Service {0} did not contain the variable "image"'.format(service_name),
None, None)
image = services[service_name]['image'].split(':')[0]
services[service_name]['image'] = '{0}:{1}'.format(image, tag)
return __dump_compose_file(path, compose_result,
'Service {0} is set to tag "{1}"'.format(service_name, tag),
already_existed=True)
|
saltstack/salt
|
salt/modules/dockercompose.py
|
up
|
python
|
def up(path, service_names=None):
'''
Create and start containers defined in the docker-compose.yml file
located in path, service_names is a python list, if omitted create and
start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will create and start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.up /path/where/docker-compose/stored
salt myminion dockercompose.up /path/where/docker-compose/stored '[janus]'
'''
debug_ret = {}
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
result = _get_convergence_plans(project, service_names)
ret = project.up(service_names)
if debug:
for container in ret:
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Adding containers via docker-compose', result, debug_ret)
|
Create and start containers defined in the docker-compose.yml file
located in path, service_names is a python list, if omitted create and
start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will create and start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.up /path/where/docker-compose/stored
salt myminion dockercompose.up /path/where/docker-compose/stored '[janus]'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockercompose.py#L857-L891
|
[
"def __standardize_result(status, message, data=None, debug_msg=None):\n '''\n Standardizes all responses\n\n :param status:\n :param message:\n :param data:\n :param debug_msg:\n :return:\n '''\n result = {\n 'status': status,\n 'message': message\n }\n\n if data is not None:\n result['return'] = data\n\n if debug_msg is not None and debug:\n result['debug'] = debug_msg\n\n return result\n",
"def __load_project(path):\n '''\n Load a docker-compose project from path\n\n :param path:\n :return:\n '''\n file_path = __get_docker_file_path(path)\n if file_path is None:\n msg = 'Could not find docker-compose file at {0}'.format(path)\n return __standardize_result(False,\n msg,\n None, None)\n return __load_project_from_file_path(file_path)\n",
"def __handle_except(inst):\n '''\n Handle exception and return a standard result\n\n :param inst:\n :return:\n '''\n return __standardize_result(False,\n 'Docker-compose command {0} failed'.\n format(inspect.stack()[1][3]),\n '{0}'.format(inst), None)\n",
"def _get_convergence_plans(project, service_names):\n '''\n Get action executed for each container\n\n :param project:\n :param service_names:\n :return:\n '''\n ret = {}\n plans = project._get_convergence_plans(project.get_services(service_names),\n ConvergenceStrategy.changed)\n for cont in plans:\n (action, container) = plans[cont]\n if action == 'create':\n ret[cont] = 'Creating container'\n elif action == 'recreate':\n ret[cont] = 'Re-creating container'\n elif action == 'start':\n ret[cont] = 'Starting container'\n elif action == 'noop':\n ret[cont] = 'Container is up to date'\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Module to import docker-compose via saltstack
.. versionadded:: 2016.3.0
:maintainer: Jean Praloran <jeanpralo@gmail.com>
:maturity: new
:depends: docker-compose>=1.5
:platform: all
Introduction
------------
This module allows one to deal with docker-compose file in a directory.
This is a first version only, the following commands are missing at the moment
but will be built later on if the community is interested in this module:
- run
- logs
- port
- scale
Installation Prerequisites
--------------------------
This execution module requires at least version 1.4.0 of both docker-compose_ and
Docker_. docker-compose can easily be installed using :py:func:`pip.install
<salt.modules.pip.install>`:
.. code-block:: bash
salt myminion pip.install docker-compose>=1.5.0
.. _docker-compose: https://pypi.python.org/pypi/docker-compose
.. _Docker: https://www.docker.com/
How to use this module?
-----------------------
In order to use the module if you have no docker-compose file on the server you
can issue the command create, it takes two arguments the path where the
docker-compose.yml will be stored and the content of this latter:
.. code-block:: text
# salt-call -l debug dockercompose.create /tmp/toto '
database:
image: mongo:3.0
command: mongod --smallfiles --quiet --logpath=/dev/null
'
Then you can execute a list of method defined at the bottom with at least one
argument (the path where the docker-compose.yml will be read) and an optional
python list which corresponds to the services names:
.. code-block:: bash
# salt-call -l debug dockercompose.up /tmp/toto
# salt-call -l debug dockercompose.restart /tmp/toto '[database]'
# salt-call -l debug dockercompose.stop /tmp/toto
# salt-call -l debug dockercompose.rm /tmp/toto
Docker-compose method supported
-------------------------------
- up
- restart
- stop
- start
- pause
- unpause
- kill
- rm
- ps
- pull
- build
Functions
---------
- docker-compose.yml management
- :py:func:`dockercompose.create <salt.modules.dockercompose.create>`
- :py:func:`dockercompose.get <salt.modules.dockercompose.get>`
- Manage containers
- :py:func:`dockercompose.restart <salt.modules.dockercompose.restart>`
- :py:func:`dockercompose.stop <salt.modules.dockercompose.stop>`
- :py:func:`dockercompose.pause <salt.modules.dockercompose.pause>`
- :py:func:`dockercompose.unpause <salt.modules.dockercompose.unpause>`
- :py:func:`dockercompose.start <salt.modules.dockercompose.start>`
- :py:func:`dockercompose.kill <salt.modules.dockercompose.kill>`
- :py:func:`dockercompose.rm <salt.modules.dockercompose.rm>`
- :py:func:`dockercompose.up <salt.modules.dockercompose.up>`
- Manage containers image:
- :py:func:`dockercompose.pull <salt.modules.dockercompose.pull>`
- :py:func:`dockercompose.build <salt.modules.dockercompose.build>`
- Gather information about containers:
- :py:func:`dockercompose.ps <salt.modules.dockercompose.ps>`
- Manage service definitions:
- :py:func:`dockercompose.service_create <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_upsert <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_remove <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_set_tag <salt.modules.dockercompose.ps>`
Detailed Function Documentation
-------------------------------
'''
from __future__ import absolute_import, print_function, unicode_literals
import inspect
import logging
import os
import re
import salt.utils.files
import salt.utils.stringutils
from salt.ext import six
from operator import attrgetter
from salt.serializers import json
from salt.utils import yaml
try:
import compose
from compose.cli.command import get_project
from compose.service import ConvergenceStrategy
HAS_DOCKERCOMPOSE = True
except ImportError:
HAS_DOCKERCOMPOSE = False
try:
from compose.project import OneOffFilter
USE_FILTERCLASS = True
except ImportError:
USE_FILTERCLASS = False
MIN_DOCKERCOMPOSE = (1, 5, 0)
VERSION_RE = r'([\d.]+)'
log = logging.getLogger(__name__)
debug = False
__virtualname__ = 'dockercompose'
DEFAULT_DC_FILENAMES = ('docker-compose.yml', 'docker-compose.yaml')
def __virtual__():
if HAS_DOCKERCOMPOSE:
match = re.match(VERSION_RE, six.text_type(compose.__version__))
if match:
version = tuple([int(x) for x in match.group(1).split('.')])
if version >= MIN_DOCKERCOMPOSE:
return __virtualname__
return (False, 'The dockercompose execution module not loaded: '
'compose python library not available.')
def __standardize_result(status, message, data=None, debug_msg=None):
'''
Standardizes all responses
:param status:
:param message:
:param data:
:param debug_msg:
:return:
'''
result = {
'status': status,
'message': message
}
if data is not None:
result['return'] = data
if debug_msg is not None and debug:
result['debug'] = debug_msg
return result
def __get_docker_file_path(path):
'''
Determines the filepath to use
:param path:
:return:
'''
if os.path.isfile(path):
return path
for dc_filename in DEFAULT_DC_FILENAMES:
file_path = os.path.join(path, dc_filename)
if os.path.isfile(file_path):
return file_path
# implicitly return None
def __read_docker_compose_file(file_path):
'''
Read the compose file if it exists in the directory
:param file_path:
:return:
'''
if not os.path.isfile(file_path):
return __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
file_name = os.path.basename(file_path)
result = {file_name: ''}
for line in fl:
result[file_name] += salt.utils.stringutils.to_unicode(line)
except EnvironmentError:
return __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
return __standardize_result(True,
'Reading content of {0}'.format(file_path),
result, None)
def __load_docker_compose(path):
'''
Read the compose file and load its' contents
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return None, __standardize_result(False, msg,
None, None)
if not os.path.isfile(file_path):
return None, __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
loaded = yaml.load(fl)
except EnvironmentError:
return None, __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(file_path, yerr)
return None, __standardize_result(False, msg,
None, None)
if not loaded:
msg = 'Got empty compose file at {0}'.format(file_path)
return None, __standardize_result(False, msg,
None, None)
if 'services' not in loaded:
loaded['services'] = {}
result = {
'compose_content': loaded,
'file_name': os.path.basename(file_path)
}
return result, None
def __dump_docker_compose(path, content, already_existed):
'''
Dumps
:param path:
:param content: the not-yet dumped content
:return:
'''
try:
dumped = yaml.safe_dump(content, indent=2, default_flow_style=False)
return __write_docker_compose(path, dumped, already_existed)
except TypeError as t_err:
msg = 'Could not dump {0} {1}'.format(content, t_err)
return __standardize_result(False, msg,
None, None)
def __write_docker_compose(path, docker_compose, already_existed):
'''
Write docker-compose to a path
in order to use it with docker-compose ( config check )
:param path:
docker_compose
contains the docker-compose file
:return:
'''
if path.lower().endswith(('.yml', '.yaml')):
file_path = path
dir_name = os.path.dirname(path)
else:
dir_name = path
file_path = os.path.join(dir_name, DEFAULT_DC_FILENAMES[0])
if os.path.isdir(dir_name) is False:
os.mkdir(dir_name)
try:
with salt.utils.files.fopen(file_path, 'w') as fl:
fl.write(salt.utils.stringutils.to_str(docker_compose))
except EnvironmentError:
return __standardize_result(False,
'Could not write {0}'.format(file_path),
None, None)
project = __load_project_from_file_path(file_path)
if isinstance(project, dict):
if not already_existed:
os.remove(file_path)
return project
return file_path
def __load_project(path):
'''
Load a docker-compose project from path
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return __standardize_result(False,
msg,
None, None)
return __load_project_from_file_path(file_path)
def __load_project_from_file_path(file_path):
'''
Load a docker-compose project from file path
:param path:
:return:
'''
try:
project = get_project(project_dir=os.path.dirname(file_path),
config_path=[os.path.basename(file_path)])
except Exception as inst:
return __handle_except(inst)
return project
def __load_compose_definitions(path, definition):
'''
Will load the compose file located at path
Then determines the format/contents of the sent definition
err or results are only set if there were any
:param path:
:param definition:
:return tuple(compose_result, loaded_definition, err):
'''
compose_result, err = __load_docker_compose(path)
if err:
return None, None, err
if isinstance(definition, dict):
return compose_result, definition, None
elif definition.strip().startswith('{'):
try:
loaded_definition = json.deserialize(definition)
except json.DeserializationError as jerr:
msg = 'Could not parse {0} {1}'.format(definition, jerr)
return None, None, __standardize_result(False, msg,
None, None)
else:
try:
loaded_definition = yaml.load(definition)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(definition, yerr)
return None, None, __standardize_result(False, msg,
None, None)
return compose_result, loaded_definition, None
def __dump_compose_file(path, compose_result, success_msg, already_existed):
'''
Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return:
'''
ret = __dump_docker_compose(path,
compose_result['compose_content'],
already_existed)
if isinstance(ret, dict):
return ret
return __standardize_result(True, success_msg,
compose_result['compose_content'], None)
def __handle_except(inst):
'''
Handle exception and return a standard result
:param inst:
:return:
'''
return __standardize_result(False,
'Docker-compose command {0} failed'.
format(inspect.stack()[1][3]),
'{0}'.format(inst), None)
def _get_convergence_plans(project, service_names):
'''
Get action executed for each container
:param project:
:param service_names:
:return:
'''
ret = {}
plans = project._get_convergence_plans(project.get_services(service_names),
ConvergenceStrategy.changed)
for cont in plans:
(action, container) = plans[cont]
if action == 'create':
ret[cont] = 'Creating container'
elif action == 'recreate':
ret[cont] = 'Re-creating container'
elif action == 'start':
ret[cont] = 'Starting container'
elif action == 'noop':
ret[cont] = 'Container is up to date'
return ret
def get(path):
'''
Get the content of the docker-compose file into a directory
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.get /path/where/docker-compose/stored
'''
file_path = __get_docker_file_path(path)
if file_path is None:
return __standardize_result(False,
'Path {} is not present'.format(path),
None, None)
salt_result = __read_docker_compose_file(file_path)
if not salt_result['status']:
return salt_result
project = __load_project(path)
if isinstance(project, dict):
salt_result['return']['valid'] = False
else:
salt_result['return']['valid'] = True
return salt_result
def create(path, docker_compose):
'''
Create and validate a docker-compose file into a directory
path
Path where the docker-compose file will be stored on the server
docker_compose
docker_compose file
CLI Example:
.. code-block:: bash
salt myminion dockercompose.create /path/where/docker-compose/stored content
'''
if docker_compose:
ret = __write_docker_compose(path,
docker_compose,
already_existed=False)
if isinstance(ret, dict):
return ret
else:
return __standardize_result(False,
'Creating a docker-compose project failed, you must send a valid docker-compose file',
None, None)
return __standardize_result(True,
'Successfully created the docker-compose file',
{'compose.base_dir': path},
None)
def pull(path, service_names=None):
'''
Pull image for containers in the docker-compose file, service_names is a
python list, if omitted pull all images
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pull /path/where/docker-compose/stored
salt myminion dockercompose.pull /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.pull(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pulling containers images via docker-compose succeeded',
None, None)
def build(path, service_names=None):
'''
Build image for containers in the docker-compose file, service_names is a
python list, if omitted build images for all containers. Please note
that at the moment the module does not allow you to upload your Dockerfile,
nor any other file you could need with your docker-compose.yml, you will
have to make sure the files you need are actually in the directory specified
in the `build` keyword
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.build /path/where/docker-compose/stored
salt myminion dockercompose.build /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.build(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Building containers images via docker-compose succeeded',
None, None)
def restart(path, service_names=None):
'''
Restart container(s) in the docker-compose file, service_names is a python
list, if omitted restart all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will restart only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.restart /path/where/docker-compose/stored
salt myminion dockercompose.restart /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.restart(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'restarted'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Restarting containers via docker-compose', result, debug_ret)
def stop(path, service_names=None):
'''
Stop running containers in the docker-compose file, service_names is a python
list, if omitted stop all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will stop only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.stop /path/where/docker-compose/stored
salt myminion dockercompose.stop /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
def pause(path, service_names=None):
'''
Pause running containers in the docker-compose file, service_names is a python
list, if omitted pause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.pause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'paused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pausing containers via docker-compose', result, debug_ret)
def unpause(path, service_names=None):
'''
Un-Pause containers in the docker-compose file, service_names is a python
list, if omitted unpause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will un-pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.unpause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'unpaused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Un-Pausing containers via docker-compose', result, debug_ret)
def start(path, service_names=None):
'''
Start containers in the docker-compose file, service_names is a python
list, if omitted start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.start /path/where/docker-compose/stored
salt myminion dockercompose.start /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.start(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'started'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Starting containers via docker-compose', result, debug_ret)
def kill(path, service_names=None):
'''
Kill containers in the docker-compose file, service_names is a python
list, if omitted kill all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will kill only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.kill /path/where/docker-compose/stored
salt myminion dockercompose.kill /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.kill(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'killed'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Killing containers via docker-compose', result, debug_ret)
def rm(path, service_names=None):
'''
Remove stopped containers in the docker-compose file, service_names is a python
list, if omitted remove all stopped containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will remove only the specified stopped services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.rm /path/where/docker-compose/stored
salt myminion dockercompose.rm /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.remove_stopped(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Removing stopped containers via docker-compose', None, None)
def ps(path):
'''
List all running containers and report some information about them
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.ps /path/where/docker-compose/stored
'''
project = __load_project(path)
result = {}
if isinstance(project, dict):
return project
else:
if USE_FILTERCLASS:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, OneOffFilter.only),
key=attrgetter('name'))
else:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, one_off=True),
key=attrgetter('name'))
for container in containers:
command = container.human_readable_command
if len(command) > 30:
command = '{0} ...'.format(command[:26])
result[container.name] = {
'id': container.id,
'name': container.name,
'command': command,
'state': container.human_readable_state,
'ports': container.human_readable_ports,
}
return __standardize_result(True, 'Listing docker-compose containers', result, None)
def service_create(path, service_name, definition):
'''
Create the definition of a docker-compose service
This fails when the service already exists
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service {0} created'.format(service_name),
already_existed=True)
def service_upsert(path, service_name, definition):
'''
Create or update the definition of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_upsert /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service definition for {0} is set'.format(service_name),
already_existed=True)
def service_remove(path, service_name):
'''
Remove the definition of a docker-compose service
This does not rm the container
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_remove /path/where/docker-compose/stored service_name
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
del services[service_name]
return __dump_compose_file(path, compose_result,
'Service {0} is removed from {1}'.format(service_name, path),
already_existed=True)
def service_set_tag(path, service_name, tag):
'''
Change the tag of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
tag
Name of the tag (often used as version) that the service image should have
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name tag
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
if 'image' not in services[service_name]:
return __standardize_result(False,
'Service {0} did not contain the variable "image"'.format(service_name),
None, None)
image = services[service_name]['image'].split(':')[0]
services[service_name]['image'] = '{0}:{1}'.format(image, tag)
return __dump_compose_file(path, compose_result,
'Service {0} is set to tag "{1}"'.format(service_name, tag),
already_existed=True)
|
saltstack/salt
|
salt/modules/dockercompose.py
|
service_upsert
|
python
|
def service_upsert(path, service_name, definition):
'''
Create or update the definition of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_upsert /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service definition for {0} is set'.format(service_name),
already_existed=True)
|
Create or update the definition of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_upsert /path/where/docker-compose/stored service_name definition
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockercompose.py#L927-L956
|
[
"def __standardize_result(status, message, data=None, debug_msg=None):\n '''\n Standardizes all responses\n\n :param status:\n :param message:\n :param data:\n :param debug_msg:\n :return:\n '''\n result = {\n 'status': status,\n 'message': message\n }\n\n if data is not None:\n result['return'] = data\n\n if debug_msg is not None and debug:\n result['debug'] = debug_msg\n\n return result\n",
"def __load_compose_definitions(path, definition):\n '''\n Will load the compose file located at path\n Then determines the format/contents of the sent definition\n\n err or results are only set if there were any\n\n :param path:\n :param definition:\n :return tuple(compose_result, loaded_definition, err):\n '''\n compose_result, err = __load_docker_compose(path)\n if err:\n return None, None, err\n if isinstance(definition, dict):\n return compose_result, definition, None\n elif definition.strip().startswith('{'):\n try:\n loaded_definition = json.deserialize(definition)\n except json.DeserializationError as jerr:\n msg = 'Could not parse {0} {1}'.format(definition, jerr)\n return None, None, __standardize_result(False, msg,\n None, None)\n else:\n try:\n loaded_definition = yaml.load(definition)\n except yaml.YAMLError as yerr:\n msg = 'Could not parse {0} {1}'.format(definition, yerr)\n return None, None, __standardize_result(False, msg,\n None, None)\n return compose_result, loaded_definition, None\n",
"def __dump_compose_file(path, compose_result, success_msg, already_existed):\n '''\n Utility function to dump the compose result to a file.\n\n :param path:\n :param compose_result:\n :param success_msg: the message to give upon success\n :return:\n '''\n ret = __dump_docker_compose(path,\n compose_result['compose_content'],\n already_existed)\n if isinstance(ret, dict):\n return ret\n return __standardize_result(True, success_msg,\n compose_result['compose_content'], None)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to import docker-compose via saltstack
.. versionadded:: 2016.3.0
:maintainer: Jean Praloran <jeanpralo@gmail.com>
:maturity: new
:depends: docker-compose>=1.5
:platform: all
Introduction
------------
This module allows one to deal with docker-compose file in a directory.
This is a first version only, the following commands are missing at the moment
but will be built later on if the community is interested in this module:
- run
- logs
- port
- scale
Installation Prerequisites
--------------------------
This execution module requires at least version 1.4.0 of both docker-compose_ and
Docker_. docker-compose can easily be installed using :py:func:`pip.install
<salt.modules.pip.install>`:
.. code-block:: bash
salt myminion pip.install docker-compose>=1.5.0
.. _docker-compose: https://pypi.python.org/pypi/docker-compose
.. _Docker: https://www.docker.com/
How to use this module?
-----------------------
In order to use the module if you have no docker-compose file on the server you
can issue the command create, it takes two arguments the path where the
docker-compose.yml will be stored and the content of this latter:
.. code-block:: text
# salt-call -l debug dockercompose.create /tmp/toto '
database:
image: mongo:3.0
command: mongod --smallfiles --quiet --logpath=/dev/null
'
Then you can execute a list of method defined at the bottom with at least one
argument (the path where the docker-compose.yml will be read) and an optional
python list which corresponds to the services names:
.. code-block:: bash
# salt-call -l debug dockercompose.up /tmp/toto
# salt-call -l debug dockercompose.restart /tmp/toto '[database]'
# salt-call -l debug dockercompose.stop /tmp/toto
# salt-call -l debug dockercompose.rm /tmp/toto
Docker-compose method supported
-------------------------------
- up
- restart
- stop
- start
- pause
- unpause
- kill
- rm
- ps
- pull
- build
Functions
---------
- docker-compose.yml management
- :py:func:`dockercompose.create <salt.modules.dockercompose.create>`
- :py:func:`dockercompose.get <salt.modules.dockercompose.get>`
- Manage containers
- :py:func:`dockercompose.restart <salt.modules.dockercompose.restart>`
- :py:func:`dockercompose.stop <salt.modules.dockercompose.stop>`
- :py:func:`dockercompose.pause <salt.modules.dockercompose.pause>`
- :py:func:`dockercompose.unpause <salt.modules.dockercompose.unpause>`
- :py:func:`dockercompose.start <salt.modules.dockercompose.start>`
- :py:func:`dockercompose.kill <salt.modules.dockercompose.kill>`
- :py:func:`dockercompose.rm <salt.modules.dockercompose.rm>`
- :py:func:`dockercompose.up <salt.modules.dockercompose.up>`
- Manage containers image:
- :py:func:`dockercompose.pull <salt.modules.dockercompose.pull>`
- :py:func:`dockercompose.build <salt.modules.dockercompose.build>`
- Gather information about containers:
- :py:func:`dockercompose.ps <salt.modules.dockercompose.ps>`
- Manage service definitions:
- :py:func:`dockercompose.service_create <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_upsert <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_remove <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_set_tag <salt.modules.dockercompose.ps>`
Detailed Function Documentation
-------------------------------
'''
from __future__ import absolute_import, print_function, unicode_literals
import inspect
import logging
import os
import re
import salt.utils.files
import salt.utils.stringutils
from salt.ext import six
from operator import attrgetter
from salt.serializers import json
from salt.utils import yaml
try:
import compose
from compose.cli.command import get_project
from compose.service import ConvergenceStrategy
HAS_DOCKERCOMPOSE = True
except ImportError:
HAS_DOCKERCOMPOSE = False
try:
from compose.project import OneOffFilter
USE_FILTERCLASS = True
except ImportError:
USE_FILTERCLASS = False
MIN_DOCKERCOMPOSE = (1, 5, 0)
VERSION_RE = r'([\d.]+)'
log = logging.getLogger(__name__)
debug = False
__virtualname__ = 'dockercompose'
DEFAULT_DC_FILENAMES = ('docker-compose.yml', 'docker-compose.yaml')
def __virtual__():
if HAS_DOCKERCOMPOSE:
match = re.match(VERSION_RE, six.text_type(compose.__version__))
if match:
version = tuple([int(x) for x in match.group(1).split('.')])
if version >= MIN_DOCKERCOMPOSE:
return __virtualname__
return (False, 'The dockercompose execution module not loaded: '
'compose python library not available.')
def __standardize_result(status, message, data=None, debug_msg=None):
'''
Standardizes all responses
:param status:
:param message:
:param data:
:param debug_msg:
:return:
'''
result = {
'status': status,
'message': message
}
if data is not None:
result['return'] = data
if debug_msg is not None and debug:
result['debug'] = debug_msg
return result
def __get_docker_file_path(path):
'''
Determines the filepath to use
:param path:
:return:
'''
if os.path.isfile(path):
return path
for dc_filename in DEFAULT_DC_FILENAMES:
file_path = os.path.join(path, dc_filename)
if os.path.isfile(file_path):
return file_path
# implicitly return None
def __read_docker_compose_file(file_path):
'''
Read the compose file if it exists in the directory
:param file_path:
:return:
'''
if not os.path.isfile(file_path):
return __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
file_name = os.path.basename(file_path)
result = {file_name: ''}
for line in fl:
result[file_name] += salt.utils.stringutils.to_unicode(line)
except EnvironmentError:
return __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
return __standardize_result(True,
'Reading content of {0}'.format(file_path),
result, None)
def __load_docker_compose(path):
'''
Read the compose file and load its' contents
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return None, __standardize_result(False, msg,
None, None)
if not os.path.isfile(file_path):
return None, __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
loaded = yaml.load(fl)
except EnvironmentError:
return None, __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(file_path, yerr)
return None, __standardize_result(False, msg,
None, None)
if not loaded:
msg = 'Got empty compose file at {0}'.format(file_path)
return None, __standardize_result(False, msg,
None, None)
if 'services' not in loaded:
loaded['services'] = {}
result = {
'compose_content': loaded,
'file_name': os.path.basename(file_path)
}
return result, None
def __dump_docker_compose(path, content, already_existed):
'''
Dumps
:param path:
:param content: the not-yet dumped content
:return:
'''
try:
dumped = yaml.safe_dump(content, indent=2, default_flow_style=False)
return __write_docker_compose(path, dumped, already_existed)
except TypeError as t_err:
msg = 'Could not dump {0} {1}'.format(content, t_err)
return __standardize_result(False, msg,
None, None)
def __write_docker_compose(path, docker_compose, already_existed):
'''
Write docker-compose to a path
in order to use it with docker-compose ( config check )
:param path:
docker_compose
contains the docker-compose file
:return:
'''
if path.lower().endswith(('.yml', '.yaml')):
file_path = path
dir_name = os.path.dirname(path)
else:
dir_name = path
file_path = os.path.join(dir_name, DEFAULT_DC_FILENAMES[0])
if os.path.isdir(dir_name) is False:
os.mkdir(dir_name)
try:
with salt.utils.files.fopen(file_path, 'w') as fl:
fl.write(salt.utils.stringutils.to_str(docker_compose))
except EnvironmentError:
return __standardize_result(False,
'Could not write {0}'.format(file_path),
None, None)
project = __load_project_from_file_path(file_path)
if isinstance(project, dict):
if not already_existed:
os.remove(file_path)
return project
return file_path
def __load_project(path):
'''
Load a docker-compose project from path
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return __standardize_result(False,
msg,
None, None)
return __load_project_from_file_path(file_path)
def __load_project_from_file_path(file_path):
'''
Load a docker-compose project from file path
:param path:
:return:
'''
try:
project = get_project(project_dir=os.path.dirname(file_path),
config_path=[os.path.basename(file_path)])
except Exception as inst:
return __handle_except(inst)
return project
def __load_compose_definitions(path, definition):
'''
Will load the compose file located at path
Then determines the format/contents of the sent definition
err or results are only set if there were any
:param path:
:param definition:
:return tuple(compose_result, loaded_definition, err):
'''
compose_result, err = __load_docker_compose(path)
if err:
return None, None, err
if isinstance(definition, dict):
return compose_result, definition, None
elif definition.strip().startswith('{'):
try:
loaded_definition = json.deserialize(definition)
except json.DeserializationError as jerr:
msg = 'Could not parse {0} {1}'.format(definition, jerr)
return None, None, __standardize_result(False, msg,
None, None)
else:
try:
loaded_definition = yaml.load(definition)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(definition, yerr)
return None, None, __standardize_result(False, msg,
None, None)
return compose_result, loaded_definition, None
def __dump_compose_file(path, compose_result, success_msg, already_existed):
'''
Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return:
'''
ret = __dump_docker_compose(path,
compose_result['compose_content'],
already_existed)
if isinstance(ret, dict):
return ret
return __standardize_result(True, success_msg,
compose_result['compose_content'], None)
def __handle_except(inst):
'''
Handle exception and return a standard result
:param inst:
:return:
'''
return __standardize_result(False,
'Docker-compose command {0} failed'.
format(inspect.stack()[1][3]),
'{0}'.format(inst), None)
def _get_convergence_plans(project, service_names):
'''
Get action executed for each container
:param project:
:param service_names:
:return:
'''
ret = {}
plans = project._get_convergence_plans(project.get_services(service_names),
ConvergenceStrategy.changed)
for cont in plans:
(action, container) = plans[cont]
if action == 'create':
ret[cont] = 'Creating container'
elif action == 'recreate':
ret[cont] = 'Re-creating container'
elif action == 'start':
ret[cont] = 'Starting container'
elif action == 'noop':
ret[cont] = 'Container is up to date'
return ret
def get(path):
'''
Get the content of the docker-compose file into a directory
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.get /path/where/docker-compose/stored
'''
file_path = __get_docker_file_path(path)
if file_path is None:
return __standardize_result(False,
'Path {} is not present'.format(path),
None, None)
salt_result = __read_docker_compose_file(file_path)
if not salt_result['status']:
return salt_result
project = __load_project(path)
if isinstance(project, dict):
salt_result['return']['valid'] = False
else:
salt_result['return']['valid'] = True
return salt_result
def create(path, docker_compose):
'''
Create and validate a docker-compose file into a directory
path
Path where the docker-compose file will be stored on the server
docker_compose
docker_compose file
CLI Example:
.. code-block:: bash
salt myminion dockercompose.create /path/where/docker-compose/stored content
'''
if docker_compose:
ret = __write_docker_compose(path,
docker_compose,
already_existed=False)
if isinstance(ret, dict):
return ret
else:
return __standardize_result(False,
'Creating a docker-compose project failed, you must send a valid docker-compose file',
None, None)
return __standardize_result(True,
'Successfully created the docker-compose file',
{'compose.base_dir': path},
None)
def pull(path, service_names=None):
'''
Pull image for containers in the docker-compose file, service_names is a
python list, if omitted pull all images
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pull /path/where/docker-compose/stored
salt myminion dockercompose.pull /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.pull(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pulling containers images via docker-compose succeeded',
None, None)
def build(path, service_names=None):
'''
Build image for containers in the docker-compose file, service_names is a
python list, if omitted build images for all containers. Please note
that at the moment the module does not allow you to upload your Dockerfile,
nor any other file you could need with your docker-compose.yml, you will
have to make sure the files you need are actually in the directory specified
in the `build` keyword
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.build /path/where/docker-compose/stored
salt myminion dockercompose.build /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.build(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Building containers images via docker-compose succeeded',
None, None)
def restart(path, service_names=None):
'''
Restart container(s) in the docker-compose file, service_names is a python
list, if omitted restart all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will restart only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.restart /path/where/docker-compose/stored
salt myminion dockercompose.restart /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.restart(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'restarted'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Restarting containers via docker-compose', result, debug_ret)
def stop(path, service_names=None):
'''
Stop running containers in the docker-compose file, service_names is a python
list, if omitted stop all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will stop only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.stop /path/where/docker-compose/stored
salt myminion dockercompose.stop /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
def pause(path, service_names=None):
'''
Pause running containers in the docker-compose file, service_names is a python
list, if omitted pause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.pause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'paused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pausing containers via docker-compose', result, debug_ret)
def unpause(path, service_names=None):
'''
Un-Pause containers in the docker-compose file, service_names is a python
list, if omitted unpause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will un-pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.unpause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'unpaused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Un-Pausing containers via docker-compose', result, debug_ret)
def start(path, service_names=None):
'''
Start containers in the docker-compose file, service_names is a python
list, if omitted start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.start /path/where/docker-compose/stored
salt myminion dockercompose.start /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.start(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'started'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Starting containers via docker-compose', result, debug_ret)
def kill(path, service_names=None):
'''
Kill containers in the docker-compose file, service_names is a python
list, if omitted kill all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will kill only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.kill /path/where/docker-compose/stored
salt myminion dockercompose.kill /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.kill(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'killed'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Killing containers via docker-compose', result, debug_ret)
def rm(path, service_names=None):
'''
Remove stopped containers in the docker-compose file, service_names is a python
list, if omitted remove all stopped containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will remove only the specified stopped services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.rm /path/where/docker-compose/stored
salt myminion dockercompose.rm /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.remove_stopped(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Removing stopped containers via docker-compose', None, None)
def ps(path):
'''
List all running containers and report some information about them
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.ps /path/where/docker-compose/stored
'''
project = __load_project(path)
result = {}
if isinstance(project, dict):
return project
else:
if USE_FILTERCLASS:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, OneOffFilter.only),
key=attrgetter('name'))
else:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, one_off=True),
key=attrgetter('name'))
for container in containers:
command = container.human_readable_command
if len(command) > 30:
command = '{0} ...'.format(command[:26])
result[container.name] = {
'id': container.id,
'name': container.name,
'command': command,
'state': container.human_readable_state,
'ports': container.human_readable_ports,
}
return __standardize_result(True, 'Listing docker-compose containers', result, None)
def up(path, service_names=None):
'''
Create and start containers defined in the docker-compose.yml file
located in path, service_names is a python list, if omitted create and
start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will create and start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.up /path/where/docker-compose/stored
salt myminion dockercompose.up /path/where/docker-compose/stored '[janus]'
'''
debug_ret = {}
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
result = _get_convergence_plans(project, service_names)
ret = project.up(service_names)
if debug:
for container in ret:
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Adding containers via docker-compose', result, debug_ret)
def service_create(path, service_name, definition):
'''
Create the definition of a docker-compose service
This fails when the service already exists
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service {0} created'.format(service_name),
already_existed=True)
def service_remove(path, service_name):
'''
Remove the definition of a docker-compose service
This does not rm the container
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_remove /path/where/docker-compose/stored service_name
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
del services[service_name]
return __dump_compose_file(path, compose_result,
'Service {0} is removed from {1}'.format(service_name, path),
already_existed=True)
def service_set_tag(path, service_name, tag):
'''
Change the tag of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
tag
Name of the tag (often used as version) that the service image should have
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name tag
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
if 'image' not in services[service_name]:
return __standardize_result(False,
'Service {0} did not contain the variable "image"'.format(service_name),
None, None)
image = services[service_name]['image'].split(':')[0]
services[service_name]['image'] = '{0}:{1}'.format(image, tag)
return __dump_compose_file(path, compose_result,
'Service {0} is set to tag "{1}"'.format(service_name, tag),
already_existed=True)
|
saltstack/salt
|
salt/modules/dockercompose.py
|
service_remove
|
python
|
def service_remove(path, service_name):
'''
Remove the definition of a docker-compose service
This does not rm the container
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_remove /path/where/docker-compose/stored service_name
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
del services[service_name]
return __dump_compose_file(path, compose_result,
'Service {0} is removed from {1}'.format(service_name, path),
already_existed=True)
|
Remove the definition of a docker-compose service
This does not rm the container
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_remove /path/where/docker-compose/stored service_name
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockercompose.py#L959-L987
|
[
"def __standardize_result(status, message, data=None, debug_msg=None):\n '''\n Standardizes all responses\n\n :param status:\n :param message:\n :param data:\n :param debug_msg:\n :return:\n '''\n result = {\n 'status': status,\n 'message': message\n }\n\n if data is not None:\n result['return'] = data\n\n if debug_msg is not None and debug:\n result['debug'] = debug_msg\n\n return result\n",
"def __load_docker_compose(path):\n '''\n Read the compose file and load its' contents\n\n :param path:\n :return:\n '''\n file_path = __get_docker_file_path(path)\n if file_path is None:\n msg = 'Could not find docker-compose file at {0}'.format(path)\n return None, __standardize_result(False, msg,\n None, None)\n if not os.path.isfile(file_path):\n return None, __standardize_result(False,\n 'Path {} is not present'.format(file_path),\n None, None)\n try:\n with salt.utils.files.fopen(file_path, 'r') as fl:\n loaded = yaml.load(fl)\n except EnvironmentError:\n return None, __standardize_result(False,\n 'Could not read {0}'.format(file_path),\n None, None)\n except yaml.YAMLError as yerr:\n msg = 'Could not parse {0} {1}'.format(file_path, yerr)\n return None, __standardize_result(False, msg,\n None, None)\n if not loaded:\n msg = 'Got empty compose file at {0}'.format(file_path)\n return None, __standardize_result(False, msg,\n None, None)\n if 'services' not in loaded:\n loaded['services'] = {}\n result = {\n 'compose_content': loaded,\n 'file_name': os.path.basename(file_path)\n }\n return result, None\n",
"def __dump_compose_file(path, compose_result, success_msg, already_existed):\n '''\n Utility function to dump the compose result to a file.\n\n :param path:\n :param compose_result:\n :param success_msg: the message to give upon success\n :return:\n '''\n ret = __dump_docker_compose(path,\n compose_result['compose_content'],\n already_existed)\n if isinstance(ret, dict):\n return ret\n return __standardize_result(True, success_msg,\n compose_result['compose_content'], None)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to import docker-compose via saltstack
.. versionadded:: 2016.3.0
:maintainer: Jean Praloran <jeanpralo@gmail.com>
:maturity: new
:depends: docker-compose>=1.5
:platform: all
Introduction
------------
This module allows one to deal with docker-compose file in a directory.
This is a first version only, the following commands are missing at the moment
but will be built later on if the community is interested in this module:
- run
- logs
- port
- scale
Installation Prerequisites
--------------------------
This execution module requires at least version 1.4.0 of both docker-compose_ and
Docker_. docker-compose can easily be installed using :py:func:`pip.install
<salt.modules.pip.install>`:
.. code-block:: bash
salt myminion pip.install docker-compose>=1.5.0
.. _docker-compose: https://pypi.python.org/pypi/docker-compose
.. _Docker: https://www.docker.com/
How to use this module?
-----------------------
In order to use the module if you have no docker-compose file on the server you
can issue the command create, it takes two arguments the path where the
docker-compose.yml will be stored and the content of this latter:
.. code-block:: text
# salt-call -l debug dockercompose.create /tmp/toto '
database:
image: mongo:3.0
command: mongod --smallfiles --quiet --logpath=/dev/null
'
Then you can execute a list of method defined at the bottom with at least one
argument (the path where the docker-compose.yml will be read) and an optional
python list which corresponds to the services names:
.. code-block:: bash
# salt-call -l debug dockercompose.up /tmp/toto
# salt-call -l debug dockercompose.restart /tmp/toto '[database]'
# salt-call -l debug dockercompose.stop /tmp/toto
# salt-call -l debug dockercompose.rm /tmp/toto
Docker-compose method supported
-------------------------------
- up
- restart
- stop
- start
- pause
- unpause
- kill
- rm
- ps
- pull
- build
Functions
---------
- docker-compose.yml management
- :py:func:`dockercompose.create <salt.modules.dockercompose.create>`
- :py:func:`dockercompose.get <salt.modules.dockercompose.get>`
- Manage containers
- :py:func:`dockercompose.restart <salt.modules.dockercompose.restart>`
- :py:func:`dockercompose.stop <salt.modules.dockercompose.stop>`
- :py:func:`dockercompose.pause <salt.modules.dockercompose.pause>`
- :py:func:`dockercompose.unpause <salt.modules.dockercompose.unpause>`
- :py:func:`dockercompose.start <salt.modules.dockercompose.start>`
- :py:func:`dockercompose.kill <salt.modules.dockercompose.kill>`
- :py:func:`dockercompose.rm <salt.modules.dockercompose.rm>`
- :py:func:`dockercompose.up <salt.modules.dockercompose.up>`
- Manage containers image:
- :py:func:`dockercompose.pull <salt.modules.dockercompose.pull>`
- :py:func:`dockercompose.build <salt.modules.dockercompose.build>`
- Gather information about containers:
- :py:func:`dockercompose.ps <salt.modules.dockercompose.ps>`
- Manage service definitions:
- :py:func:`dockercompose.service_create <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_upsert <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_remove <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_set_tag <salt.modules.dockercompose.ps>`
Detailed Function Documentation
-------------------------------
'''
from __future__ import absolute_import, print_function, unicode_literals
import inspect
import logging
import os
import re
import salt.utils.files
import salt.utils.stringutils
from salt.ext import six
from operator import attrgetter
from salt.serializers import json
from salt.utils import yaml
try:
import compose
from compose.cli.command import get_project
from compose.service import ConvergenceStrategy
HAS_DOCKERCOMPOSE = True
except ImportError:
HAS_DOCKERCOMPOSE = False
try:
from compose.project import OneOffFilter
USE_FILTERCLASS = True
except ImportError:
USE_FILTERCLASS = False
MIN_DOCKERCOMPOSE = (1, 5, 0)
VERSION_RE = r'([\d.]+)'
log = logging.getLogger(__name__)
debug = False
__virtualname__ = 'dockercompose'
DEFAULT_DC_FILENAMES = ('docker-compose.yml', 'docker-compose.yaml')
def __virtual__():
if HAS_DOCKERCOMPOSE:
match = re.match(VERSION_RE, six.text_type(compose.__version__))
if match:
version = tuple([int(x) for x in match.group(1).split('.')])
if version >= MIN_DOCKERCOMPOSE:
return __virtualname__
return (False, 'The dockercompose execution module not loaded: '
'compose python library not available.')
def __standardize_result(status, message, data=None, debug_msg=None):
'''
Standardizes all responses
:param status:
:param message:
:param data:
:param debug_msg:
:return:
'''
result = {
'status': status,
'message': message
}
if data is not None:
result['return'] = data
if debug_msg is not None and debug:
result['debug'] = debug_msg
return result
def __get_docker_file_path(path):
'''
Determines the filepath to use
:param path:
:return:
'''
if os.path.isfile(path):
return path
for dc_filename in DEFAULT_DC_FILENAMES:
file_path = os.path.join(path, dc_filename)
if os.path.isfile(file_path):
return file_path
# implicitly return None
def __read_docker_compose_file(file_path):
'''
Read the compose file if it exists in the directory
:param file_path:
:return:
'''
if not os.path.isfile(file_path):
return __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
file_name = os.path.basename(file_path)
result = {file_name: ''}
for line in fl:
result[file_name] += salt.utils.stringutils.to_unicode(line)
except EnvironmentError:
return __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
return __standardize_result(True,
'Reading content of {0}'.format(file_path),
result, None)
def __load_docker_compose(path):
'''
Read the compose file and load its' contents
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return None, __standardize_result(False, msg,
None, None)
if not os.path.isfile(file_path):
return None, __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
loaded = yaml.load(fl)
except EnvironmentError:
return None, __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(file_path, yerr)
return None, __standardize_result(False, msg,
None, None)
if not loaded:
msg = 'Got empty compose file at {0}'.format(file_path)
return None, __standardize_result(False, msg,
None, None)
if 'services' not in loaded:
loaded['services'] = {}
result = {
'compose_content': loaded,
'file_name': os.path.basename(file_path)
}
return result, None
def __dump_docker_compose(path, content, already_existed):
'''
Dumps
:param path:
:param content: the not-yet dumped content
:return:
'''
try:
dumped = yaml.safe_dump(content, indent=2, default_flow_style=False)
return __write_docker_compose(path, dumped, already_existed)
except TypeError as t_err:
msg = 'Could not dump {0} {1}'.format(content, t_err)
return __standardize_result(False, msg,
None, None)
def __write_docker_compose(path, docker_compose, already_existed):
'''
Write docker-compose to a path
in order to use it with docker-compose ( config check )
:param path:
docker_compose
contains the docker-compose file
:return:
'''
if path.lower().endswith(('.yml', '.yaml')):
file_path = path
dir_name = os.path.dirname(path)
else:
dir_name = path
file_path = os.path.join(dir_name, DEFAULT_DC_FILENAMES[0])
if os.path.isdir(dir_name) is False:
os.mkdir(dir_name)
try:
with salt.utils.files.fopen(file_path, 'w') as fl:
fl.write(salt.utils.stringutils.to_str(docker_compose))
except EnvironmentError:
return __standardize_result(False,
'Could not write {0}'.format(file_path),
None, None)
project = __load_project_from_file_path(file_path)
if isinstance(project, dict):
if not already_existed:
os.remove(file_path)
return project
return file_path
def __load_project(path):
'''
Load a docker-compose project from path
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return __standardize_result(False,
msg,
None, None)
return __load_project_from_file_path(file_path)
def __load_project_from_file_path(file_path):
'''
Load a docker-compose project from file path
:param path:
:return:
'''
try:
project = get_project(project_dir=os.path.dirname(file_path),
config_path=[os.path.basename(file_path)])
except Exception as inst:
return __handle_except(inst)
return project
def __load_compose_definitions(path, definition):
'''
Will load the compose file located at path
Then determines the format/contents of the sent definition
err or results are only set if there were any
:param path:
:param definition:
:return tuple(compose_result, loaded_definition, err):
'''
compose_result, err = __load_docker_compose(path)
if err:
return None, None, err
if isinstance(definition, dict):
return compose_result, definition, None
elif definition.strip().startswith('{'):
try:
loaded_definition = json.deserialize(definition)
except json.DeserializationError as jerr:
msg = 'Could not parse {0} {1}'.format(definition, jerr)
return None, None, __standardize_result(False, msg,
None, None)
else:
try:
loaded_definition = yaml.load(definition)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(definition, yerr)
return None, None, __standardize_result(False, msg,
None, None)
return compose_result, loaded_definition, None
def __dump_compose_file(path, compose_result, success_msg, already_existed):
'''
Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return:
'''
ret = __dump_docker_compose(path,
compose_result['compose_content'],
already_existed)
if isinstance(ret, dict):
return ret
return __standardize_result(True, success_msg,
compose_result['compose_content'], None)
def __handle_except(inst):
'''
Handle exception and return a standard result
:param inst:
:return:
'''
return __standardize_result(False,
'Docker-compose command {0} failed'.
format(inspect.stack()[1][3]),
'{0}'.format(inst), None)
def _get_convergence_plans(project, service_names):
'''
Get action executed for each container
:param project:
:param service_names:
:return:
'''
ret = {}
plans = project._get_convergence_plans(project.get_services(service_names),
ConvergenceStrategy.changed)
for cont in plans:
(action, container) = plans[cont]
if action == 'create':
ret[cont] = 'Creating container'
elif action == 'recreate':
ret[cont] = 'Re-creating container'
elif action == 'start':
ret[cont] = 'Starting container'
elif action == 'noop':
ret[cont] = 'Container is up to date'
return ret
def get(path):
'''
Get the content of the docker-compose file into a directory
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.get /path/where/docker-compose/stored
'''
file_path = __get_docker_file_path(path)
if file_path is None:
return __standardize_result(False,
'Path {} is not present'.format(path),
None, None)
salt_result = __read_docker_compose_file(file_path)
if not salt_result['status']:
return salt_result
project = __load_project(path)
if isinstance(project, dict):
salt_result['return']['valid'] = False
else:
salt_result['return']['valid'] = True
return salt_result
def create(path, docker_compose):
'''
Create and validate a docker-compose file into a directory
path
Path where the docker-compose file will be stored on the server
docker_compose
docker_compose file
CLI Example:
.. code-block:: bash
salt myminion dockercompose.create /path/where/docker-compose/stored content
'''
if docker_compose:
ret = __write_docker_compose(path,
docker_compose,
already_existed=False)
if isinstance(ret, dict):
return ret
else:
return __standardize_result(False,
'Creating a docker-compose project failed, you must send a valid docker-compose file',
None, None)
return __standardize_result(True,
'Successfully created the docker-compose file',
{'compose.base_dir': path},
None)
def pull(path, service_names=None):
'''
Pull image for containers in the docker-compose file, service_names is a
python list, if omitted pull all images
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pull /path/where/docker-compose/stored
salt myminion dockercompose.pull /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.pull(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pulling containers images via docker-compose succeeded',
None, None)
def build(path, service_names=None):
'''
Build image for containers in the docker-compose file, service_names is a
python list, if omitted build images for all containers. Please note
that at the moment the module does not allow you to upload your Dockerfile,
nor any other file you could need with your docker-compose.yml, you will
have to make sure the files you need are actually in the directory specified
in the `build` keyword
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.build /path/where/docker-compose/stored
salt myminion dockercompose.build /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.build(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Building containers images via docker-compose succeeded',
None, None)
def restart(path, service_names=None):
'''
Restart container(s) in the docker-compose file, service_names is a python
list, if omitted restart all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will restart only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.restart /path/where/docker-compose/stored
salt myminion dockercompose.restart /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.restart(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'restarted'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Restarting containers via docker-compose', result, debug_ret)
def stop(path, service_names=None):
'''
Stop running containers in the docker-compose file, service_names is a python
list, if omitted stop all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will stop only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.stop /path/where/docker-compose/stored
salt myminion dockercompose.stop /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
def pause(path, service_names=None):
'''
Pause running containers in the docker-compose file, service_names is a python
list, if omitted pause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.pause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'paused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pausing containers via docker-compose', result, debug_ret)
def unpause(path, service_names=None):
'''
Un-Pause containers in the docker-compose file, service_names is a python
list, if omitted unpause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will un-pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.unpause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'unpaused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Un-Pausing containers via docker-compose', result, debug_ret)
def start(path, service_names=None):
'''
Start containers in the docker-compose file, service_names is a python
list, if omitted start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.start /path/where/docker-compose/stored
salt myminion dockercompose.start /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.start(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'started'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Starting containers via docker-compose', result, debug_ret)
def kill(path, service_names=None):
'''
Kill containers in the docker-compose file, service_names is a python
list, if omitted kill all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will kill only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.kill /path/where/docker-compose/stored
salt myminion dockercompose.kill /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.kill(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'killed'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Killing containers via docker-compose', result, debug_ret)
def rm(path, service_names=None):
'''
Remove stopped containers in the docker-compose file, service_names is a python
list, if omitted remove all stopped containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will remove only the specified stopped services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.rm /path/where/docker-compose/stored
salt myminion dockercompose.rm /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.remove_stopped(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Removing stopped containers via docker-compose', None, None)
def ps(path):
'''
List all running containers and report some information about them
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.ps /path/where/docker-compose/stored
'''
project = __load_project(path)
result = {}
if isinstance(project, dict):
return project
else:
if USE_FILTERCLASS:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, OneOffFilter.only),
key=attrgetter('name'))
else:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, one_off=True),
key=attrgetter('name'))
for container in containers:
command = container.human_readable_command
if len(command) > 30:
command = '{0} ...'.format(command[:26])
result[container.name] = {
'id': container.id,
'name': container.name,
'command': command,
'state': container.human_readable_state,
'ports': container.human_readable_ports,
}
return __standardize_result(True, 'Listing docker-compose containers', result, None)
def up(path, service_names=None):
'''
Create and start containers defined in the docker-compose.yml file
located in path, service_names is a python list, if omitted create and
start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will create and start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.up /path/where/docker-compose/stored
salt myminion dockercompose.up /path/where/docker-compose/stored '[janus]'
'''
debug_ret = {}
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
result = _get_convergence_plans(project, service_names)
ret = project.up(service_names)
if debug:
for container in ret:
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Adding containers via docker-compose', result, debug_ret)
def service_create(path, service_name, definition):
'''
Create the definition of a docker-compose service
This fails when the service already exists
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service {0} created'.format(service_name),
already_existed=True)
def service_upsert(path, service_name, definition):
'''
Create or update the definition of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_upsert /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service definition for {0} is set'.format(service_name),
already_existed=True)
def service_set_tag(path, service_name, tag):
'''
Change the tag of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
tag
Name of the tag (often used as version) that the service image should have
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name tag
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
if 'image' not in services[service_name]:
return __standardize_result(False,
'Service {0} did not contain the variable "image"'.format(service_name),
None, None)
image = services[service_name]['image'].split(':')[0]
services[service_name]['image'] = '{0}:{1}'.format(image, tag)
return __dump_compose_file(path, compose_result,
'Service {0} is set to tag "{1}"'.format(service_name, tag),
already_existed=True)
|
saltstack/salt
|
salt/modules/dockercompose.py
|
service_set_tag
|
python
|
def service_set_tag(path, service_name, tag):
'''
Change the tag of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
tag
Name of the tag (often used as version) that the service image should have
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name tag
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
if 'image' not in services[service_name]:
return __standardize_result(False,
'Service {0} did not contain the variable "image"'.format(service_name),
None, None)
image = services[service_name]['image'].split(':')[0]
services[service_name]['image'] = '{0}:{1}'.format(image, tag)
return __dump_compose_file(path, compose_result,
'Service {0} is set to tag "{1}"'.format(service_name, tag),
already_existed=True)
|
Change the tag of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
tag
Name of the tag (often used as version) that the service image should have
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name tag
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/dockercompose.py#L990-L1025
|
[
"def __standardize_result(status, message, data=None, debug_msg=None):\n '''\n Standardizes all responses\n\n :param status:\n :param message:\n :param data:\n :param debug_msg:\n :return:\n '''\n result = {\n 'status': status,\n 'message': message\n }\n\n if data is not None:\n result['return'] = data\n\n if debug_msg is not None and debug:\n result['debug'] = debug_msg\n\n return result\n",
"def __load_docker_compose(path):\n '''\n Read the compose file and load its' contents\n\n :param path:\n :return:\n '''\n file_path = __get_docker_file_path(path)\n if file_path is None:\n msg = 'Could not find docker-compose file at {0}'.format(path)\n return None, __standardize_result(False, msg,\n None, None)\n if not os.path.isfile(file_path):\n return None, __standardize_result(False,\n 'Path {} is not present'.format(file_path),\n None, None)\n try:\n with salt.utils.files.fopen(file_path, 'r') as fl:\n loaded = yaml.load(fl)\n except EnvironmentError:\n return None, __standardize_result(False,\n 'Could not read {0}'.format(file_path),\n None, None)\n except yaml.YAMLError as yerr:\n msg = 'Could not parse {0} {1}'.format(file_path, yerr)\n return None, __standardize_result(False, msg,\n None, None)\n if not loaded:\n msg = 'Got empty compose file at {0}'.format(file_path)\n return None, __standardize_result(False, msg,\n None, None)\n if 'services' not in loaded:\n loaded['services'] = {}\n result = {\n 'compose_content': loaded,\n 'file_name': os.path.basename(file_path)\n }\n return result, None\n",
"def __dump_compose_file(path, compose_result, success_msg, already_existed):\n '''\n Utility function to dump the compose result to a file.\n\n :param path:\n :param compose_result:\n :param success_msg: the message to give upon success\n :return:\n '''\n ret = __dump_docker_compose(path,\n compose_result['compose_content'],\n already_existed)\n if isinstance(ret, dict):\n return ret\n return __standardize_result(True, success_msg,\n compose_result['compose_content'], None)\n"
] |
# -*- coding: utf-8 -*-
'''
Module to import docker-compose via saltstack
.. versionadded:: 2016.3.0
:maintainer: Jean Praloran <jeanpralo@gmail.com>
:maturity: new
:depends: docker-compose>=1.5
:platform: all
Introduction
------------
This module allows one to deal with docker-compose file in a directory.
This is a first version only, the following commands are missing at the moment
but will be built later on if the community is interested in this module:
- run
- logs
- port
- scale
Installation Prerequisites
--------------------------
This execution module requires at least version 1.4.0 of both docker-compose_ and
Docker_. docker-compose can easily be installed using :py:func:`pip.install
<salt.modules.pip.install>`:
.. code-block:: bash
salt myminion pip.install docker-compose>=1.5.0
.. _docker-compose: https://pypi.python.org/pypi/docker-compose
.. _Docker: https://www.docker.com/
How to use this module?
-----------------------
In order to use the module if you have no docker-compose file on the server you
can issue the command create, it takes two arguments the path where the
docker-compose.yml will be stored and the content of this latter:
.. code-block:: text
# salt-call -l debug dockercompose.create /tmp/toto '
database:
image: mongo:3.0
command: mongod --smallfiles --quiet --logpath=/dev/null
'
Then you can execute a list of method defined at the bottom with at least one
argument (the path where the docker-compose.yml will be read) and an optional
python list which corresponds to the services names:
.. code-block:: bash
# salt-call -l debug dockercompose.up /tmp/toto
# salt-call -l debug dockercompose.restart /tmp/toto '[database]'
# salt-call -l debug dockercompose.stop /tmp/toto
# salt-call -l debug dockercompose.rm /tmp/toto
Docker-compose method supported
-------------------------------
- up
- restart
- stop
- start
- pause
- unpause
- kill
- rm
- ps
- pull
- build
Functions
---------
- docker-compose.yml management
- :py:func:`dockercompose.create <salt.modules.dockercompose.create>`
- :py:func:`dockercompose.get <salt.modules.dockercompose.get>`
- Manage containers
- :py:func:`dockercompose.restart <salt.modules.dockercompose.restart>`
- :py:func:`dockercompose.stop <salt.modules.dockercompose.stop>`
- :py:func:`dockercompose.pause <salt.modules.dockercompose.pause>`
- :py:func:`dockercompose.unpause <salt.modules.dockercompose.unpause>`
- :py:func:`dockercompose.start <salt.modules.dockercompose.start>`
- :py:func:`dockercompose.kill <salt.modules.dockercompose.kill>`
- :py:func:`dockercompose.rm <salt.modules.dockercompose.rm>`
- :py:func:`dockercompose.up <salt.modules.dockercompose.up>`
- Manage containers image:
- :py:func:`dockercompose.pull <salt.modules.dockercompose.pull>`
- :py:func:`dockercompose.build <salt.modules.dockercompose.build>`
- Gather information about containers:
- :py:func:`dockercompose.ps <salt.modules.dockercompose.ps>`
- Manage service definitions:
- :py:func:`dockercompose.service_create <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_upsert <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_remove <salt.modules.dockercompose.ps>`
- :py:func:`dockercompose.service_set_tag <salt.modules.dockercompose.ps>`
Detailed Function Documentation
-------------------------------
'''
from __future__ import absolute_import, print_function, unicode_literals
import inspect
import logging
import os
import re
import salt.utils.files
import salt.utils.stringutils
from salt.ext import six
from operator import attrgetter
from salt.serializers import json
from salt.utils import yaml
try:
import compose
from compose.cli.command import get_project
from compose.service import ConvergenceStrategy
HAS_DOCKERCOMPOSE = True
except ImportError:
HAS_DOCKERCOMPOSE = False
try:
from compose.project import OneOffFilter
USE_FILTERCLASS = True
except ImportError:
USE_FILTERCLASS = False
MIN_DOCKERCOMPOSE = (1, 5, 0)
VERSION_RE = r'([\d.]+)'
log = logging.getLogger(__name__)
debug = False
__virtualname__ = 'dockercompose'
DEFAULT_DC_FILENAMES = ('docker-compose.yml', 'docker-compose.yaml')
def __virtual__():
if HAS_DOCKERCOMPOSE:
match = re.match(VERSION_RE, six.text_type(compose.__version__))
if match:
version = tuple([int(x) for x in match.group(1).split('.')])
if version >= MIN_DOCKERCOMPOSE:
return __virtualname__
return (False, 'The dockercompose execution module not loaded: '
'compose python library not available.')
def __standardize_result(status, message, data=None, debug_msg=None):
'''
Standardizes all responses
:param status:
:param message:
:param data:
:param debug_msg:
:return:
'''
result = {
'status': status,
'message': message
}
if data is not None:
result['return'] = data
if debug_msg is not None and debug:
result['debug'] = debug_msg
return result
def __get_docker_file_path(path):
'''
Determines the filepath to use
:param path:
:return:
'''
if os.path.isfile(path):
return path
for dc_filename in DEFAULT_DC_FILENAMES:
file_path = os.path.join(path, dc_filename)
if os.path.isfile(file_path):
return file_path
# implicitly return None
def __read_docker_compose_file(file_path):
'''
Read the compose file if it exists in the directory
:param file_path:
:return:
'''
if not os.path.isfile(file_path):
return __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
file_name = os.path.basename(file_path)
result = {file_name: ''}
for line in fl:
result[file_name] += salt.utils.stringutils.to_unicode(line)
except EnvironmentError:
return __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
return __standardize_result(True,
'Reading content of {0}'.format(file_path),
result, None)
def __load_docker_compose(path):
'''
Read the compose file and load its' contents
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return None, __standardize_result(False, msg,
None, None)
if not os.path.isfile(file_path):
return None, __standardize_result(False,
'Path {} is not present'.format(file_path),
None, None)
try:
with salt.utils.files.fopen(file_path, 'r') as fl:
loaded = yaml.load(fl)
except EnvironmentError:
return None, __standardize_result(False,
'Could not read {0}'.format(file_path),
None, None)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(file_path, yerr)
return None, __standardize_result(False, msg,
None, None)
if not loaded:
msg = 'Got empty compose file at {0}'.format(file_path)
return None, __standardize_result(False, msg,
None, None)
if 'services' not in loaded:
loaded['services'] = {}
result = {
'compose_content': loaded,
'file_name': os.path.basename(file_path)
}
return result, None
def __dump_docker_compose(path, content, already_existed):
'''
Dumps
:param path:
:param content: the not-yet dumped content
:return:
'''
try:
dumped = yaml.safe_dump(content, indent=2, default_flow_style=False)
return __write_docker_compose(path, dumped, already_existed)
except TypeError as t_err:
msg = 'Could not dump {0} {1}'.format(content, t_err)
return __standardize_result(False, msg,
None, None)
def __write_docker_compose(path, docker_compose, already_existed):
'''
Write docker-compose to a path
in order to use it with docker-compose ( config check )
:param path:
docker_compose
contains the docker-compose file
:return:
'''
if path.lower().endswith(('.yml', '.yaml')):
file_path = path
dir_name = os.path.dirname(path)
else:
dir_name = path
file_path = os.path.join(dir_name, DEFAULT_DC_FILENAMES[0])
if os.path.isdir(dir_name) is False:
os.mkdir(dir_name)
try:
with salt.utils.files.fopen(file_path, 'w') as fl:
fl.write(salt.utils.stringutils.to_str(docker_compose))
except EnvironmentError:
return __standardize_result(False,
'Could not write {0}'.format(file_path),
None, None)
project = __load_project_from_file_path(file_path)
if isinstance(project, dict):
if not already_existed:
os.remove(file_path)
return project
return file_path
def __load_project(path):
'''
Load a docker-compose project from path
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return __standardize_result(False,
msg,
None, None)
return __load_project_from_file_path(file_path)
def __load_project_from_file_path(file_path):
'''
Load a docker-compose project from file path
:param path:
:return:
'''
try:
project = get_project(project_dir=os.path.dirname(file_path),
config_path=[os.path.basename(file_path)])
except Exception as inst:
return __handle_except(inst)
return project
def __load_compose_definitions(path, definition):
'''
Will load the compose file located at path
Then determines the format/contents of the sent definition
err or results are only set if there were any
:param path:
:param definition:
:return tuple(compose_result, loaded_definition, err):
'''
compose_result, err = __load_docker_compose(path)
if err:
return None, None, err
if isinstance(definition, dict):
return compose_result, definition, None
elif definition.strip().startswith('{'):
try:
loaded_definition = json.deserialize(definition)
except json.DeserializationError as jerr:
msg = 'Could not parse {0} {1}'.format(definition, jerr)
return None, None, __standardize_result(False, msg,
None, None)
else:
try:
loaded_definition = yaml.load(definition)
except yaml.YAMLError as yerr:
msg = 'Could not parse {0} {1}'.format(definition, yerr)
return None, None, __standardize_result(False, msg,
None, None)
return compose_result, loaded_definition, None
def __dump_compose_file(path, compose_result, success_msg, already_existed):
'''
Utility function to dump the compose result to a file.
:param path:
:param compose_result:
:param success_msg: the message to give upon success
:return:
'''
ret = __dump_docker_compose(path,
compose_result['compose_content'],
already_existed)
if isinstance(ret, dict):
return ret
return __standardize_result(True, success_msg,
compose_result['compose_content'], None)
def __handle_except(inst):
'''
Handle exception and return a standard result
:param inst:
:return:
'''
return __standardize_result(False,
'Docker-compose command {0} failed'.
format(inspect.stack()[1][3]),
'{0}'.format(inst), None)
def _get_convergence_plans(project, service_names):
'''
Get action executed for each container
:param project:
:param service_names:
:return:
'''
ret = {}
plans = project._get_convergence_plans(project.get_services(service_names),
ConvergenceStrategy.changed)
for cont in plans:
(action, container) = plans[cont]
if action == 'create':
ret[cont] = 'Creating container'
elif action == 'recreate':
ret[cont] = 'Re-creating container'
elif action == 'start':
ret[cont] = 'Starting container'
elif action == 'noop':
ret[cont] = 'Container is up to date'
return ret
def get(path):
'''
Get the content of the docker-compose file into a directory
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.get /path/where/docker-compose/stored
'''
file_path = __get_docker_file_path(path)
if file_path is None:
return __standardize_result(False,
'Path {} is not present'.format(path),
None, None)
salt_result = __read_docker_compose_file(file_path)
if not salt_result['status']:
return salt_result
project = __load_project(path)
if isinstance(project, dict):
salt_result['return']['valid'] = False
else:
salt_result['return']['valid'] = True
return salt_result
def create(path, docker_compose):
'''
Create and validate a docker-compose file into a directory
path
Path where the docker-compose file will be stored on the server
docker_compose
docker_compose file
CLI Example:
.. code-block:: bash
salt myminion dockercompose.create /path/where/docker-compose/stored content
'''
if docker_compose:
ret = __write_docker_compose(path,
docker_compose,
already_existed=False)
if isinstance(ret, dict):
return ret
else:
return __standardize_result(False,
'Creating a docker-compose project failed, you must send a valid docker-compose file',
None, None)
return __standardize_result(True,
'Successfully created the docker-compose file',
{'compose.base_dir': path},
None)
def pull(path, service_names=None):
'''
Pull image for containers in the docker-compose file, service_names is a
python list, if omitted pull all images
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pull /path/where/docker-compose/stored
salt myminion dockercompose.pull /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.pull(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pulling containers images via docker-compose succeeded',
None, None)
def build(path, service_names=None):
'''
Build image for containers in the docker-compose file, service_names is a
python list, if omitted build images for all containers. Please note
that at the moment the module does not allow you to upload your Dockerfile,
nor any other file you could need with your docker-compose.yml, you will
have to make sure the files you need are actually in the directory specified
in the `build` keyword
path
Path where the docker-compose file is stored on the server
service_names
If specified will pull only the image for the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.build /path/where/docker-compose/stored
salt myminion dockercompose.build /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.build(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Building containers images via docker-compose succeeded',
None, None)
def restart(path, service_names=None):
'''
Restart container(s) in the docker-compose file, service_names is a python
list, if omitted restart all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will restart only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.restart /path/where/docker-compose/stored
salt myminion dockercompose.restart /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.restart(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'restarted'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Restarting containers via docker-compose', result, debug_ret)
def stop(path, service_names=None):
'''
Stop running containers in the docker-compose file, service_names is a python
list, if omitted stop all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will stop only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.stop /path/where/docker-compose/stored
salt myminion dockercompose.stop /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.stop(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'stopped'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Stopping containers via docker-compose', result, debug_ret)
def pause(path, service_names=None):
'''
Pause running containers in the docker-compose file, service_names is a python
list, if omitted pause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.pause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'paused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Pausing containers via docker-compose', result, debug_ret)
def unpause(path, service_names=None):
'''
Un-Pause containers in the docker-compose file, service_names is a python
list, if omitted unpause all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will un-pause only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.pause /path/where/docker-compose/stored
salt myminion dockercompose.pause /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.unpause(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'unpaused'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Un-Pausing containers via docker-compose', result, debug_ret)
def start(path, service_names=None):
'''
Start containers in the docker-compose file, service_names is a python
list, if omitted start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.start /path/where/docker-compose/stored
salt myminion dockercompose.start /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.start(service_names)
if debug:
for container in project.containers():
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'started'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Starting containers via docker-compose', result, debug_ret)
def kill(path, service_names=None):
'''
Kill containers in the docker-compose file, service_names is a python
list, if omitted kill all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will kill only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.kill /path/where/docker-compose/stored
salt myminion dockercompose.kill /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
debug_ret = {}
result = {}
if isinstance(project, dict):
return project
else:
try:
project.kill(service_names)
if debug:
for container in project.containers(stopped=True):
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
result[container.get('Name')] = 'killed'
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Killing containers via docker-compose', result, debug_ret)
def rm(path, service_names=None):
'''
Remove stopped containers in the docker-compose file, service_names is a python
list, if omitted remove all stopped containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will remove only the specified stopped services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.rm /path/where/docker-compose/stored
salt myminion dockercompose.rm /path/where/docker-compose/stored '[janus]'
'''
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
project.remove_stopped(service_names)
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Removing stopped containers via docker-compose', None, None)
def ps(path):
'''
List all running containers and report some information about them
path
Path where the docker-compose file is stored on the server
CLI Example:
.. code-block:: bash
salt myminion dockercompose.ps /path/where/docker-compose/stored
'''
project = __load_project(path)
result = {}
if isinstance(project, dict):
return project
else:
if USE_FILTERCLASS:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, OneOffFilter.only),
key=attrgetter('name'))
else:
containers = sorted(
project.containers(None, stopped=True) +
project.containers(None, one_off=True),
key=attrgetter('name'))
for container in containers:
command = container.human_readable_command
if len(command) > 30:
command = '{0} ...'.format(command[:26])
result[container.name] = {
'id': container.id,
'name': container.name,
'command': command,
'state': container.human_readable_state,
'ports': container.human_readable_ports,
}
return __standardize_result(True, 'Listing docker-compose containers', result, None)
def up(path, service_names=None):
'''
Create and start containers defined in the docker-compose.yml file
located in path, service_names is a python list, if omitted create and
start all containers
path
Path where the docker-compose file is stored on the server
service_names
If specified will create and start only the specified services
CLI Example:
.. code-block:: bash
salt myminion dockercompose.up /path/where/docker-compose/stored
salt myminion dockercompose.up /path/where/docker-compose/stored '[janus]'
'''
debug_ret = {}
project = __load_project(path)
if isinstance(project, dict):
return project
else:
try:
result = _get_convergence_plans(project, service_names)
ret = project.up(service_names)
if debug:
for container in ret:
if service_names is None or container.get('Name')[1:] in service_names:
container.inspect_if_not_inspected()
debug_ret[container.get('Name')] = container.inspect()
except Exception as inst:
return __handle_except(inst)
return __standardize_result(True, 'Adding containers via docker-compose', result, debug_ret)
def service_create(path, service_name, definition):
'''
Create the definition of a docker-compose service
This fails when the service already exists
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_create /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service {0} created'.format(service_name),
already_existed=True)
def service_upsert(path, service_name, definition):
'''
Create or update the definition of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to create
definition
Service definition as yaml or json string
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_upsert /path/where/docker-compose/stored service_name definition
'''
compose_result, loaded_definition, err = __load_compose_definitions(path, definition)
if err:
return err
services = compose_result['compose_content']['services']
if service_name in services:
msg = 'Service {0} already exists'.format(service_name)
return __standardize_result(False, msg, None, None)
services[service_name] = loaded_definition
return __dump_compose_file(path, compose_result,
'Service definition for {0} is set'.format(service_name),
already_existed=True)
def service_remove(path, service_name):
'''
Remove the definition of a docker-compose service
This does not rm the container
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
CLI Example:
.. code-block:: bash
salt myminion dockercompose.service_remove /path/where/docker-compose/stored service_name
'''
compose_result, err = __load_docker_compose(path)
if err:
return err
services = compose_result['compose_content']['services']
if service_name not in services:
return __standardize_result(False,
'Service {0} did not exists'.format(service_name),
None, None)
del services[service_name]
return __dump_compose_file(path, compose_result,
'Service {0} is removed from {1}'.format(service_name, path),
already_existed=True)
|
saltstack/salt
|
salt/state.py
|
split_low_tag
|
python
|
def split_low_tag(tag):
'''
Take a low tag and split it back into the low dict that it came from
'''
state, id_, name, fun = tag.split('_|-')
return {'state': state,
'__id__': id_,
'name': name,
'fun': fun}
|
Take a low tag and split it back into the low dict that it came from
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L144-L153
| null |
# -*- coding: utf-8 -*-
'''
The State Compiler is used to execute states in Salt. A state is unlike
an execution module in that instead of just executing a command, it
ensures that a certain state is present on the system.
The data sent to the state calls is as follows:
{ 'state': '<state module name>',
'fun': '<state function name>',
'name': '<the name argument passed to all states>'
'argn': '<arbitrary argument, can have many of these>'
}
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import copy
import site
import fnmatch
import logging
import datetime
import traceback
import re
import time
import random
import collections
# Import salt libs
import salt.loader
import salt.minion
import salt.pillar
import salt.fileclient
import salt.utils.args
import salt.utils.crypt
import salt.utils.data
import salt.utils.decorators.state
import salt.utils.dictupdate
import salt.utils.event
import salt.utils.files
import salt.utils.hashutils
import salt.utils.immutabletypes as immutabletypes
import salt.utils.msgpack as msgpack
import salt.utils.platform
import salt.utils.process
import salt.utils.url
import salt.syspaths as syspaths
import salt.transport.client
from salt.serializers.msgpack import serialize as msgpack_serialize, deserialize as msgpack_deserialize
from salt.template import compile_template, compile_template_str
from salt.exceptions import (
SaltRenderError,
SaltReqTimeoutError
)
from salt.utils.odict import OrderedDict, DefaultOrderedDict
# Explicit late import to avoid circular import. DO NOT MOVE THIS.
import salt.utils.yamlloader as yamlloader
# Import third party libs
# pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext import six
from salt.ext.six.moves import map, range, reload_module
# pylint: enable=import-error,no-name-in-module,redefined-builtin
log = logging.getLogger(__name__)
# These are keywords passed to state module functions which are to be used
# by salt in this state module and not on the actual state module function
STATE_REQUISITE_KEYWORDS = frozenset([
'onchanges',
'onchanges_any',
'onfail',
'onfail_any',
'onfail_all',
'onfail_stop',
'prereq',
'prerequired',
'watch',
'watch_any',
'require',
'require_any',
'listen',
])
STATE_REQUISITE_IN_KEYWORDS = frozenset([
'onchanges_in',
'onfail_in',
'prereq_in',
'watch_in',
'require_in',
'listen_in',
])
STATE_RUNTIME_KEYWORDS = frozenset([
'fun',
'state',
'check_cmd',
'failhard',
'onlyif',
'unless',
'retry',
'order',
'parallel',
'prereq',
'prereq_in',
'prerequired',
'reload_modules',
'reload_grains',
'reload_pillar',
'runas',
'runas_password',
'fire_event',
'saltenv',
'use',
'use_in',
'__env__',
'__sls__',
'__id__',
'__orchestration_jid__',
'__pub_user',
'__pub_arg',
'__pub_id',
'__pub_jid',
'__pub_fun',
'__pub_fun_args',
'__pub_schedule',
'__pub_tgt',
'__pub_ret',
'__pub_pid',
'__pub_tgt_type',
'__prereq__',
])
STATE_INTERNAL_KEYWORDS = STATE_REQUISITE_KEYWORDS.union(STATE_REQUISITE_IN_KEYWORDS).union(STATE_RUNTIME_KEYWORDS)
def _odict_hashable(self):
return id(self)
OrderedDict.__hash__ = _odict_hashable
def _gen_tag(low):
'''
Generate the running dict tag string from the low data structure
'''
return '{0[state]}_|-{0[__id__]}_|-{0[name]}_|-{0[fun]}'.format(low)
def _clean_tag(tag):
'''
Make tag name safe for filenames
'''
return salt.utils.files.safe_filename_leaf(tag)
def _l_tag(name, id_):
low = {'name': 'listen_{0}'.format(name),
'__id__': 'listen_{0}'.format(id_),
'state': 'Listen_Error',
'fun': 'Listen_Error'}
return _gen_tag(low)
def _calculate_fake_duration():
'''
Generate a NULL duration for when states do not run
but we want the results to be consistent.
'''
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - \
(datetime.datetime.utcnow() - datetime.datetime.now())
utc_finish_time = datetime.datetime.utcnow()
start_time = local_start_time.time().isoformat()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
return start_time, duration
def get_accumulator_dir(cachedir):
'''
Return the directory that accumulator data is stored in, creating it if it
doesn't exist.
'''
fn_ = os.path.join(cachedir, 'accumulator')
if not os.path.isdir(fn_):
# accumulator_dir is not present, create it
os.makedirs(fn_)
return fn_
def trim_req(req):
'''
Trim any function off of a requisite
'''
reqfirst = next(iter(req))
if '.' in reqfirst:
return {reqfirst.split('.')[0]: req[reqfirst]}
return req
def state_args(id_, state, high):
'''
Return a set of the arguments passed to the named state
'''
args = set()
if id_ not in high:
return args
if state not in high[id_]:
return args
for item in high[id_][state]:
if not isinstance(item, dict):
continue
if len(item) != 1:
continue
args.add(next(iter(item)))
return args
def find_name(name, state, high):
'''
Scan high data for the id referencing the given name and return a list of (IDs, state) tuples that match
Note: if `state` is sls, then we are looking for all IDs that match the given SLS
'''
ext_id = []
if name in high:
ext_id.append((name, state))
# if we are requiring an entire SLS, then we need to add ourselves to everything in that SLS
elif state == 'sls':
for nid, item in six.iteritems(high):
if item['__sls__'] == name:
ext_id.append((nid, next(iter(item))))
# otherwise we are requiring a single state, lets find it
else:
# We need to scan for the name
for nid in high:
if state in high[nid]:
if isinstance(high[nid][state], list):
for arg in high[nid][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if arg[next(iter(arg))] == name:
ext_id.append((nid, state))
return ext_id
def find_sls_ids(sls, high):
'''
Scan for all ids in the given sls and return them in a dict; {name: state}
'''
ret = []
for nid, item in six.iteritems(high):
try:
sls_tgt = item['__sls__']
except TypeError:
if nid != '__exclude__':
log.error(
'Invalid non-dict item \'%s\' in high data. Value: %r',
nid, item
)
continue
else:
if sls_tgt == sls:
for st_ in item:
if st_.startswith('__'):
continue
ret.append((nid, st_))
return ret
def format_log(ret):
'''
Format the state into a log message
'''
msg = ''
if isinstance(ret, dict):
# Looks like the ret may be a valid state return
if 'changes' in ret:
# Yep, looks like a valid state return
chg = ret['changes']
if not chg:
if ret['comment']:
msg = ret['comment']
else:
msg = 'No changes made for {0[name]}'.format(ret)
elif isinstance(chg, dict):
if 'diff' in chg:
if isinstance(chg['diff'], six.string_types):
msg = 'File changed:\n{0}'.format(chg['diff'])
if all([isinstance(x, dict) for x in six.itervalues(chg)]):
if all([('old' in x and 'new' in x)
for x in six.itervalues(chg)]):
msg = 'Made the following changes:\n'
for pkg in chg:
old = chg[pkg]['old']
if not old and old not in (False, None):
old = 'absent'
new = chg[pkg]['new']
if not new and new not in (False, None):
new = 'absent'
# This must be able to handle unicode as some package names contain
# non-ascii characters like "Français" or "Español". See Issue #33605.
msg += '\'{0}\' changed from \'{1}\' to \'{2}\'\n'.format(pkg, old, new)
if not msg:
msg = six.text_type(ret['changes'])
if ret['result'] is True or ret['result'] is None:
log.info(msg)
else:
log.error(msg)
else:
# catch unhandled data
log.info(six.text_type(ret))
def master_compile(master_opts, minion_opts, grains, id_, saltenv):
'''
Compile the master side low state data, and build the hidden state file
'''
st_ = MasterHighState(master_opts, minion_opts, grains, id_, saltenv)
return st_.compile_highstate()
def ishashable(obj):
try:
hash(obj)
except TypeError:
return False
return True
def mock_ret(cdata):
'''
Returns a mocked return dict with information about the run, without
executing the state function
'''
# As this is expanded it should be sent into the execution module
# layer or it should be turned into a standalone loader system
if cdata['args']:
name = cdata['args'][0]
else:
name = cdata['kwargs']['name']
return {'name': name,
'comment': 'Not called, mocked',
'changes': {},
'result': True}
class StateError(Exception):
'''
Custom exception class.
'''
pass
class Compiler(object):
'''
Class used to compile and manage the High Data structure
'''
def __init__(self, opts, renderers):
self.opts = opts
self.rend = renderers
def render_template(self, template, **kwargs):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'],
**kwargs)
if not high:
return high
return self.pad_funcs(high)
def pad_funcs(self, high):
'''
Turns dot delimited function refs into function strings
'''
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state? It needs to be padded!
if '.' in high[name]:
comps = high[name].split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}'.format(
name,
body['__sls__'],
type(name).__name__
)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(('The {0}'
' statement in state \'{1}\' in SLS \'{2}\' '
'needs to be formed as a list').format(
argfirst,
name,
body['__sls__']
))
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = {'state': state}
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append((
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
))
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'is SLS {1}\n'
).format(
six.text_type(req_val),
body['__sls__']))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(('Multiple dictionaries '
'defined in argument of state \'{0}\' in SLS'
' \'{1}\'').format(
name,
body['__sls__']))
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(('No function declared in state \'{0}\' in'
' SLS \'{1}\'').format(state, body['__sls__']))
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunk['name'] = salt.utils.data.decode(chunk['name'])
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = {'state': state,
'name': name}
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
continue
else:
chunk.update(arg)
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order = name_order + 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associtaed ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if body.get('__sls__', '') in ex_sls:
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
class HighState(BaseHighState):
'''
Generate and execute the salt "High State". The High State is the
compound state derived from a group of template files stored on the
salt master or in the local cache.
'''
# a stack of active HighState objects during a state.highstate run
stack = []
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.opts = opts
self.client = salt.fileclient.get_file_client(self.opts)
BaseHighState.__init__(self, opts)
self.state = State(self.opts,
pillar_override,
jid,
pillar_enc,
proxy=proxy,
context=context,
mocked=mocked,
loader=loader,
initial_pillar=initial_pillar)
self.matchers = salt.loader.matchers(self.opts)
self.proxy = proxy
# tracks all pydsl state declarations globally across sls files
self._pydsl_all_decls = {}
# a stack of current rendering Sls objects, maintained and used by the pydsl renderer.
self._pydsl_render_stack = []
def push_active(self):
self.stack.append(self)
@classmethod
def clear_active(cls):
# Nuclear option
#
# Blow away the entire stack. Used primarily by the test runner but also
# useful in custom wrappers of the HighState class, to reset the stack
# to a fresh state.
cls.stack = []
@classmethod
def pop_active(cls):
cls.stack.pop()
@classmethod
def get_active(cls):
try:
return cls.stack[-1]
except IndexError:
return None
class MasterState(State):
'''
Create a State object for master side compiling
'''
def __init__(self, opts, minion):
State.__init__(self, opts)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
# Load a modified client interface that looks like the interface used
# from the minion, but uses remote execution
#
self.functions = salt.client.FunctionWrapper(
self.opts,
self.opts['id']
)
# Load the states, but they should not be used in this class apart
# from inspection
self.utils = salt.loader.utils(self.opts)
self.serializers = salt.loader.serializers(self.opts)
self.states = salt.loader.states(self.opts, self.functions, self.utils, self.serializers)
self.rend = salt.loader.render(self.opts, self.functions, states=self.states, context=self.state_con)
class MasterHighState(HighState):
'''
Execute highstate compilation from the master
'''
def __init__(self, master_opts, minion_opts, grains, id_,
saltenv=None):
# Force the fileclient to be local
opts = copy.deepcopy(minion_opts)
opts['file_client'] = 'local'
opts['file_roots'] = master_opts['master_roots']
opts['renderer'] = master_opts['renderer']
opts['state_top'] = master_opts['state_top']
opts['id'] = id_
opts['grains'] = grains
HighState.__init__(self, opts)
class RemoteHighState(object):
'''
Manage gathering the data from the master
'''
# XXX: This class doesn't seem to be used anywhere
def __init__(self, opts, grains):
self.opts = opts
self.grains = grains
self.serial = salt.payload.Serial(self.opts)
# self.auth = salt.crypt.SAuth(opts)
self.channel = salt.transport.client.ReqChannel.factory(self.opts['master_uri'])
self._closing = False
def compile_master(self):
'''
Return the state data from the master
'''
load = {'grains': self.grains,
'opts': self.opts,
'cmd': '_master_state'}
try:
return self.channel.send(load, tries=3, timeout=72000)
except SaltReqTimeoutError:
return {}
def destroy(self):
if self._closing:
return
self._closing = True
self.channel.close()
def __del__(self):
self.destroy()
|
saltstack/salt
|
salt/state.py
|
_calculate_fake_duration
|
python
|
def _calculate_fake_duration():
'''
Generate a NULL duration for when states do not run
but we want the results to be consistent.
'''
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - \
(datetime.datetime.utcnow() - datetime.datetime.now())
utc_finish_time = datetime.datetime.utcnow()
start_time = local_start_time.time().isoformat()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
return start_time, duration
|
Generate a NULL duration for when states do not run
but we want the results to be consistent.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L178-L192
| null |
# -*- coding: utf-8 -*-
'''
The State Compiler is used to execute states in Salt. A state is unlike
an execution module in that instead of just executing a command, it
ensures that a certain state is present on the system.
The data sent to the state calls is as follows:
{ 'state': '<state module name>',
'fun': '<state function name>',
'name': '<the name argument passed to all states>'
'argn': '<arbitrary argument, can have many of these>'
}
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import copy
import site
import fnmatch
import logging
import datetime
import traceback
import re
import time
import random
import collections
# Import salt libs
import salt.loader
import salt.minion
import salt.pillar
import salt.fileclient
import salt.utils.args
import salt.utils.crypt
import salt.utils.data
import salt.utils.decorators.state
import salt.utils.dictupdate
import salt.utils.event
import salt.utils.files
import salt.utils.hashutils
import salt.utils.immutabletypes as immutabletypes
import salt.utils.msgpack as msgpack
import salt.utils.platform
import salt.utils.process
import salt.utils.url
import salt.syspaths as syspaths
import salt.transport.client
from salt.serializers.msgpack import serialize as msgpack_serialize, deserialize as msgpack_deserialize
from salt.template import compile_template, compile_template_str
from salt.exceptions import (
SaltRenderError,
SaltReqTimeoutError
)
from salt.utils.odict import OrderedDict, DefaultOrderedDict
# Explicit late import to avoid circular import. DO NOT MOVE THIS.
import salt.utils.yamlloader as yamlloader
# Import third party libs
# pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext import six
from salt.ext.six.moves import map, range, reload_module
# pylint: enable=import-error,no-name-in-module,redefined-builtin
log = logging.getLogger(__name__)
# These are keywords passed to state module functions which are to be used
# by salt in this state module and not on the actual state module function
STATE_REQUISITE_KEYWORDS = frozenset([
'onchanges',
'onchanges_any',
'onfail',
'onfail_any',
'onfail_all',
'onfail_stop',
'prereq',
'prerequired',
'watch',
'watch_any',
'require',
'require_any',
'listen',
])
STATE_REQUISITE_IN_KEYWORDS = frozenset([
'onchanges_in',
'onfail_in',
'prereq_in',
'watch_in',
'require_in',
'listen_in',
])
STATE_RUNTIME_KEYWORDS = frozenset([
'fun',
'state',
'check_cmd',
'failhard',
'onlyif',
'unless',
'retry',
'order',
'parallel',
'prereq',
'prereq_in',
'prerequired',
'reload_modules',
'reload_grains',
'reload_pillar',
'runas',
'runas_password',
'fire_event',
'saltenv',
'use',
'use_in',
'__env__',
'__sls__',
'__id__',
'__orchestration_jid__',
'__pub_user',
'__pub_arg',
'__pub_id',
'__pub_jid',
'__pub_fun',
'__pub_fun_args',
'__pub_schedule',
'__pub_tgt',
'__pub_ret',
'__pub_pid',
'__pub_tgt_type',
'__prereq__',
])
STATE_INTERNAL_KEYWORDS = STATE_REQUISITE_KEYWORDS.union(STATE_REQUISITE_IN_KEYWORDS).union(STATE_RUNTIME_KEYWORDS)
def _odict_hashable(self):
return id(self)
OrderedDict.__hash__ = _odict_hashable
def split_low_tag(tag):
'''
Take a low tag and split it back into the low dict that it came from
'''
state, id_, name, fun = tag.split('_|-')
return {'state': state,
'__id__': id_,
'name': name,
'fun': fun}
def _gen_tag(low):
'''
Generate the running dict tag string from the low data structure
'''
return '{0[state]}_|-{0[__id__]}_|-{0[name]}_|-{0[fun]}'.format(low)
def _clean_tag(tag):
'''
Make tag name safe for filenames
'''
return salt.utils.files.safe_filename_leaf(tag)
def _l_tag(name, id_):
low = {'name': 'listen_{0}'.format(name),
'__id__': 'listen_{0}'.format(id_),
'state': 'Listen_Error',
'fun': 'Listen_Error'}
return _gen_tag(low)
def get_accumulator_dir(cachedir):
'''
Return the directory that accumulator data is stored in, creating it if it
doesn't exist.
'''
fn_ = os.path.join(cachedir, 'accumulator')
if not os.path.isdir(fn_):
# accumulator_dir is not present, create it
os.makedirs(fn_)
return fn_
def trim_req(req):
'''
Trim any function off of a requisite
'''
reqfirst = next(iter(req))
if '.' in reqfirst:
return {reqfirst.split('.')[0]: req[reqfirst]}
return req
def state_args(id_, state, high):
'''
Return a set of the arguments passed to the named state
'''
args = set()
if id_ not in high:
return args
if state not in high[id_]:
return args
for item in high[id_][state]:
if not isinstance(item, dict):
continue
if len(item) != 1:
continue
args.add(next(iter(item)))
return args
def find_name(name, state, high):
'''
Scan high data for the id referencing the given name and return a list of (IDs, state) tuples that match
Note: if `state` is sls, then we are looking for all IDs that match the given SLS
'''
ext_id = []
if name in high:
ext_id.append((name, state))
# if we are requiring an entire SLS, then we need to add ourselves to everything in that SLS
elif state == 'sls':
for nid, item in six.iteritems(high):
if item['__sls__'] == name:
ext_id.append((nid, next(iter(item))))
# otherwise we are requiring a single state, lets find it
else:
# We need to scan for the name
for nid in high:
if state in high[nid]:
if isinstance(high[nid][state], list):
for arg in high[nid][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if arg[next(iter(arg))] == name:
ext_id.append((nid, state))
return ext_id
def find_sls_ids(sls, high):
'''
Scan for all ids in the given sls and return them in a dict; {name: state}
'''
ret = []
for nid, item in six.iteritems(high):
try:
sls_tgt = item['__sls__']
except TypeError:
if nid != '__exclude__':
log.error(
'Invalid non-dict item \'%s\' in high data. Value: %r',
nid, item
)
continue
else:
if sls_tgt == sls:
for st_ in item:
if st_.startswith('__'):
continue
ret.append((nid, st_))
return ret
def format_log(ret):
'''
Format the state into a log message
'''
msg = ''
if isinstance(ret, dict):
# Looks like the ret may be a valid state return
if 'changes' in ret:
# Yep, looks like a valid state return
chg = ret['changes']
if not chg:
if ret['comment']:
msg = ret['comment']
else:
msg = 'No changes made for {0[name]}'.format(ret)
elif isinstance(chg, dict):
if 'diff' in chg:
if isinstance(chg['diff'], six.string_types):
msg = 'File changed:\n{0}'.format(chg['diff'])
if all([isinstance(x, dict) for x in six.itervalues(chg)]):
if all([('old' in x and 'new' in x)
for x in six.itervalues(chg)]):
msg = 'Made the following changes:\n'
for pkg in chg:
old = chg[pkg]['old']
if not old and old not in (False, None):
old = 'absent'
new = chg[pkg]['new']
if not new and new not in (False, None):
new = 'absent'
# This must be able to handle unicode as some package names contain
# non-ascii characters like "Français" or "Español". See Issue #33605.
msg += '\'{0}\' changed from \'{1}\' to \'{2}\'\n'.format(pkg, old, new)
if not msg:
msg = six.text_type(ret['changes'])
if ret['result'] is True or ret['result'] is None:
log.info(msg)
else:
log.error(msg)
else:
# catch unhandled data
log.info(six.text_type(ret))
def master_compile(master_opts, minion_opts, grains, id_, saltenv):
'''
Compile the master side low state data, and build the hidden state file
'''
st_ = MasterHighState(master_opts, minion_opts, grains, id_, saltenv)
return st_.compile_highstate()
def ishashable(obj):
try:
hash(obj)
except TypeError:
return False
return True
def mock_ret(cdata):
'''
Returns a mocked return dict with information about the run, without
executing the state function
'''
# As this is expanded it should be sent into the execution module
# layer or it should be turned into a standalone loader system
if cdata['args']:
name = cdata['args'][0]
else:
name = cdata['kwargs']['name']
return {'name': name,
'comment': 'Not called, mocked',
'changes': {},
'result': True}
class StateError(Exception):
'''
Custom exception class.
'''
pass
class Compiler(object):
'''
Class used to compile and manage the High Data structure
'''
def __init__(self, opts, renderers):
self.opts = opts
self.rend = renderers
def render_template(self, template, **kwargs):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'],
**kwargs)
if not high:
return high
return self.pad_funcs(high)
def pad_funcs(self, high):
'''
Turns dot delimited function refs into function strings
'''
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state? It needs to be padded!
if '.' in high[name]:
comps = high[name].split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}'.format(
name,
body['__sls__'],
type(name).__name__
)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(('The {0}'
' statement in state \'{1}\' in SLS \'{2}\' '
'needs to be formed as a list').format(
argfirst,
name,
body['__sls__']
))
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = {'state': state}
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append((
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
))
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'is SLS {1}\n'
).format(
six.text_type(req_val),
body['__sls__']))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(('Multiple dictionaries '
'defined in argument of state \'{0}\' in SLS'
' \'{1}\'').format(
name,
body['__sls__']))
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(('No function declared in state \'{0}\' in'
' SLS \'{1}\'').format(state, body['__sls__']))
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunk['name'] = salt.utils.data.decode(chunk['name'])
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = {'state': state,
'name': name}
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
continue
else:
chunk.update(arg)
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order = name_order + 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associtaed ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if body.get('__sls__', '') in ex_sls:
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
class HighState(BaseHighState):
'''
Generate and execute the salt "High State". The High State is the
compound state derived from a group of template files stored on the
salt master or in the local cache.
'''
# a stack of active HighState objects during a state.highstate run
stack = []
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.opts = opts
self.client = salt.fileclient.get_file_client(self.opts)
BaseHighState.__init__(self, opts)
self.state = State(self.opts,
pillar_override,
jid,
pillar_enc,
proxy=proxy,
context=context,
mocked=mocked,
loader=loader,
initial_pillar=initial_pillar)
self.matchers = salt.loader.matchers(self.opts)
self.proxy = proxy
# tracks all pydsl state declarations globally across sls files
self._pydsl_all_decls = {}
# a stack of current rendering Sls objects, maintained and used by the pydsl renderer.
self._pydsl_render_stack = []
def push_active(self):
self.stack.append(self)
@classmethod
def clear_active(cls):
# Nuclear option
#
# Blow away the entire stack. Used primarily by the test runner but also
# useful in custom wrappers of the HighState class, to reset the stack
# to a fresh state.
cls.stack = []
@classmethod
def pop_active(cls):
cls.stack.pop()
@classmethod
def get_active(cls):
try:
return cls.stack[-1]
except IndexError:
return None
class MasterState(State):
'''
Create a State object for master side compiling
'''
def __init__(self, opts, minion):
State.__init__(self, opts)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
# Load a modified client interface that looks like the interface used
# from the minion, but uses remote execution
#
self.functions = salt.client.FunctionWrapper(
self.opts,
self.opts['id']
)
# Load the states, but they should not be used in this class apart
# from inspection
self.utils = salt.loader.utils(self.opts)
self.serializers = salt.loader.serializers(self.opts)
self.states = salt.loader.states(self.opts, self.functions, self.utils, self.serializers)
self.rend = salt.loader.render(self.opts, self.functions, states=self.states, context=self.state_con)
class MasterHighState(HighState):
'''
Execute highstate compilation from the master
'''
def __init__(self, master_opts, minion_opts, grains, id_,
saltenv=None):
# Force the fileclient to be local
opts = copy.deepcopy(minion_opts)
opts['file_client'] = 'local'
opts['file_roots'] = master_opts['master_roots']
opts['renderer'] = master_opts['renderer']
opts['state_top'] = master_opts['state_top']
opts['id'] = id_
opts['grains'] = grains
HighState.__init__(self, opts)
class RemoteHighState(object):
'''
Manage gathering the data from the master
'''
# XXX: This class doesn't seem to be used anywhere
def __init__(self, opts, grains):
self.opts = opts
self.grains = grains
self.serial = salt.payload.Serial(self.opts)
# self.auth = salt.crypt.SAuth(opts)
self.channel = salt.transport.client.ReqChannel.factory(self.opts['master_uri'])
self._closing = False
def compile_master(self):
'''
Return the state data from the master
'''
load = {'grains': self.grains,
'opts': self.opts,
'cmd': '_master_state'}
try:
return self.channel.send(load, tries=3, timeout=72000)
except SaltReqTimeoutError:
return {}
def destroy(self):
if self._closing:
return
self._closing = True
self.channel.close()
def __del__(self):
self.destroy()
|
saltstack/salt
|
salt/state.py
|
get_accumulator_dir
|
python
|
def get_accumulator_dir(cachedir):
'''
Return the directory that accumulator data is stored in, creating it if it
doesn't exist.
'''
fn_ = os.path.join(cachedir, 'accumulator')
if not os.path.isdir(fn_):
# accumulator_dir is not present, create it
os.makedirs(fn_)
return fn_
|
Return the directory that accumulator data is stored in, creating it if it
doesn't exist.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L195-L204
| null |
# -*- coding: utf-8 -*-
'''
The State Compiler is used to execute states in Salt. A state is unlike
an execution module in that instead of just executing a command, it
ensures that a certain state is present on the system.
The data sent to the state calls is as follows:
{ 'state': '<state module name>',
'fun': '<state function name>',
'name': '<the name argument passed to all states>'
'argn': '<arbitrary argument, can have many of these>'
}
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import copy
import site
import fnmatch
import logging
import datetime
import traceback
import re
import time
import random
import collections
# Import salt libs
import salt.loader
import salt.minion
import salt.pillar
import salt.fileclient
import salt.utils.args
import salt.utils.crypt
import salt.utils.data
import salt.utils.decorators.state
import salt.utils.dictupdate
import salt.utils.event
import salt.utils.files
import salt.utils.hashutils
import salt.utils.immutabletypes as immutabletypes
import salt.utils.msgpack as msgpack
import salt.utils.platform
import salt.utils.process
import salt.utils.url
import salt.syspaths as syspaths
import salt.transport.client
from salt.serializers.msgpack import serialize as msgpack_serialize, deserialize as msgpack_deserialize
from salt.template import compile_template, compile_template_str
from salt.exceptions import (
SaltRenderError,
SaltReqTimeoutError
)
from salt.utils.odict import OrderedDict, DefaultOrderedDict
# Explicit late import to avoid circular import. DO NOT MOVE THIS.
import salt.utils.yamlloader as yamlloader
# Import third party libs
# pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext import six
from salt.ext.six.moves import map, range, reload_module
# pylint: enable=import-error,no-name-in-module,redefined-builtin
log = logging.getLogger(__name__)
# These are keywords passed to state module functions which are to be used
# by salt in this state module and not on the actual state module function
STATE_REQUISITE_KEYWORDS = frozenset([
'onchanges',
'onchanges_any',
'onfail',
'onfail_any',
'onfail_all',
'onfail_stop',
'prereq',
'prerequired',
'watch',
'watch_any',
'require',
'require_any',
'listen',
])
STATE_REQUISITE_IN_KEYWORDS = frozenset([
'onchanges_in',
'onfail_in',
'prereq_in',
'watch_in',
'require_in',
'listen_in',
])
STATE_RUNTIME_KEYWORDS = frozenset([
'fun',
'state',
'check_cmd',
'failhard',
'onlyif',
'unless',
'retry',
'order',
'parallel',
'prereq',
'prereq_in',
'prerequired',
'reload_modules',
'reload_grains',
'reload_pillar',
'runas',
'runas_password',
'fire_event',
'saltenv',
'use',
'use_in',
'__env__',
'__sls__',
'__id__',
'__orchestration_jid__',
'__pub_user',
'__pub_arg',
'__pub_id',
'__pub_jid',
'__pub_fun',
'__pub_fun_args',
'__pub_schedule',
'__pub_tgt',
'__pub_ret',
'__pub_pid',
'__pub_tgt_type',
'__prereq__',
])
STATE_INTERNAL_KEYWORDS = STATE_REQUISITE_KEYWORDS.union(STATE_REQUISITE_IN_KEYWORDS).union(STATE_RUNTIME_KEYWORDS)
def _odict_hashable(self):
return id(self)
OrderedDict.__hash__ = _odict_hashable
def split_low_tag(tag):
'''
Take a low tag and split it back into the low dict that it came from
'''
state, id_, name, fun = tag.split('_|-')
return {'state': state,
'__id__': id_,
'name': name,
'fun': fun}
def _gen_tag(low):
'''
Generate the running dict tag string from the low data structure
'''
return '{0[state]}_|-{0[__id__]}_|-{0[name]}_|-{0[fun]}'.format(low)
def _clean_tag(tag):
'''
Make tag name safe for filenames
'''
return salt.utils.files.safe_filename_leaf(tag)
def _l_tag(name, id_):
low = {'name': 'listen_{0}'.format(name),
'__id__': 'listen_{0}'.format(id_),
'state': 'Listen_Error',
'fun': 'Listen_Error'}
return _gen_tag(low)
def _calculate_fake_duration():
'''
Generate a NULL duration for when states do not run
but we want the results to be consistent.
'''
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - \
(datetime.datetime.utcnow() - datetime.datetime.now())
utc_finish_time = datetime.datetime.utcnow()
start_time = local_start_time.time().isoformat()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
return start_time, duration
def trim_req(req):
'''
Trim any function off of a requisite
'''
reqfirst = next(iter(req))
if '.' in reqfirst:
return {reqfirst.split('.')[0]: req[reqfirst]}
return req
def state_args(id_, state, high):
'''
Return a set of the arguments passed to the named state
'''
args = set()
if id_ not in high:
return args
if state not in high[id_]:
return args
for item in high[id_][state]:
if not isinstance(item, dict):
continue
if len(item) != 1:
continue
args.add(next(iter(item)))
return args
def find_name(name, state, high):
'''
Scan high data for the id referencing the given name and return a list of (IDs, state) tuples that match
Note: if `state` is sls, then we are looking for all IDs that match the given SLS
'''
ext_id = []
if name in high:
ext_id.append((name, state))
# if we are requiring an entire SLS, then we need to add ourselves to everything in that SLS
elif state == 'sls':
for nid, item in six.iteritems(high):
if item['__sls__'] == name:
ext_id.append((nid, next(iter(item))))
# otherwise we are requiring a single state, lets find it
else:
# We need to scan for the name
for nid in high:
if state in high[nid]:
if isinstance(high[nid][state], list):
for arg in high[nid][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if arg[next(iter(arg))] == name:
ext_id.append((nid, state))
return ext_id
def find_sls_ids(sls, high):
'''
Scan for all ids in the given sls and return them in a dict; {name: state}
'''
ret = []
for nid, item in six.iteritems(high):
try:
sls_tgt = item['__sls__']
except TypeError:
if nid != '__exclude__':
log.error(
'Invalid non-dict item \'%s\' in high data. Value: %r',
nid, item
)
continue
else:
if sls_tgt == sls:
for st_ in item:
if st_.startswith('__'):
continue
ret.append((nid, st_))
return ret
def format_log(ret):
'''
Format the state into a log message
'''
msg = ''
if isinstance(ret, dict):
# Looks like the ret may be a valid state return
if 'changes' in ret:
# Yep, looks like a valid state return
chg = ret['changes']
if not chg:
if ret['comment']:
msg = ret['comment']
else:
msg = 'No changes made for {0[name]}'.format(ret)
elif isinstance(chg, dict):
if 'diff' in chg:
if isinstance(chg['diff'], six.string_types):
msg = 'File changed:\n{0}'.format(chg['diff'])
if all([isinstance(x, dict) for x in six.itervalues(chg)]):
if all([('old' in x and 'new' in x)
for x in six.itervalues(chg)]):
msg = 'Made the following changes:\n'
for pkg in chg:
old = chg[pkg]['old']
if not old and old not in (False, None):
old = 'absent'
new = chg[pkg]['new']
if not new and new not in (False, None):
new = 'absent'
# This must be able to handle unicode as some package names contain
# non-ascii characters like "Français" or "Español". See Issue #33605.
msg += '\'{0}\' changed from \'{1}\' to \'{2}\'\n'.format(pkg, old, new)
if not msg:
msg = six.text_type(ret['changes'])
if ret['result'] is True or ret['result'] is None:
log.info(msg)
else:
log.error(msg)
else:
# catch unhandled data
log.info(six.text_type(ret))
def master_compile(master_opts, minion_opts, grains, id_, saltenv):
'''
Compile the master side low state data, and build the hidden state file
'''
st_ = MasterHighState(master_opts, minion_opts, grains, id_, saltenv)
return st_.compile_highstate()
def ishashable(obj):
try:
hash(obj)
except TypeError:
return False
return True
def mock_ret(cdata):
'''
Returns a mocked return dict with information about the run, without
executing the state function
'''
# As this is expanded it should be sent into the execution module
# layer or it should be turned into a standalone loader system
if cdata['args']:
name = cdata['args'][0]
else:
name = cdata['kwargs']['name']
return {'name': name,
'comment': 'Not called, mocked',
'changes': {},
'result': True}
class StateError(Exception):
'''
Custom exception class.
'''
pass
class Compiler(object):
'''
Class used to compile and manage the High Data structure
'''
def __init__(self, opts, renderers):
self.opts = opts
self.rend = renderers
def render_template(self, template, **kwargs):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'],
**kwargs)
if not high:
return high
return self.pad_funcs(high)
def pad_funcs(self, high):
'''
Turns dot delimited function refs into function strings
'''
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state? It needs to be padded!
if '.' in high[name]:
comps = high[name].split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}'.format(
name,
body['__sls__'],
type(name).__name__
)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(('The {0}'
' statement in state \'{1}\' in SLS \'{2}\' '
'needs to be formed as a list').format(
argfirst,
name,
body['__sls__']
))
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = {'state': state}
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append((
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
))
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'is SLS {1}\n'
).format(
six.text_type(req_val),
body['__sls__']))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(('Multiple dictionaries '
'defined in argument of state \'{0}\' in SLS'
' \'{1}\'').format(
name,
body['__sls__']))
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(('No function declared in state \'{0}\' in'
' SLS \'{1}\'').format(state, body['__sls__']))
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunk['name'] = salt.utils.data.decode(chunk['name'])
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = {'state': state,
'name': name}
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
continue
else:
chunk.update(arg)
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order = name_order + 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associtaed ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if body.get('__sls__', '') in ex_sls:
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
class HighState(BaseHighState):
'''
Generate and execute the salt "High State". The High State is the
compound state derived from a group of template files stored on the
salt master or in the local cache.
'''
# a stack of active HighState objects during a state.highstate run
stack = []
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.opts = opts
self.client = salt.fileclient.get_file_client(self.opts)
BaseHighState.__init__(self, opts)
self.state = State(self.opts,
pillar_override,
jid,
pillar_enc,
proxy=proxy,
context=context,
mocked=mocked,
loader=loader,
initial_pillar=initial_pillar)
self.matchers = salt.loader.matchers(self.opts)
self.proxy = proxy
# tracks all pydsl state declarations globally across sls files
self._pydsl_all_decls = {}
# a stack of current rendering Sls objects, maintained and used by the pydsl renderer.
self._pydsl_render_stack = []
def push_active(self):
self.stack.append(self)
@classmethod
def clear_active(cls):
# Nuclear option
#
# Blow away the entire stack. Used primarily by the test runner but also
# useful in custom wrappers of the HighState class, to reset the stack
# to a fresh state.
cls.stack = []
@classmethod
def pop_active(cls):
cls.stack.pop()
@classmethod
def get_active(cls):
try:
return cls.stack[-1]
except IndexError:
return None
class MasterState(State):
'''
Create a State object for master side compiling
'''
def __init__(self, opts, minion):
State.__init__(self, opts)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
# Load a modified client interface that looks like the interface used
# from the minion, but uses remote execution
#
self.functions = salt.client.FunctionWrapper(
self.opts,
self.opts['id']
)
# Load the states, but they should not be used in this class apart
# from inspection
self.utils = salt.loader.utils(self.opts)
self.serializers = salt.loader.serializers(self.opts)
self.states = salt.loader.states(self.opts, self.functions, self.utils, self.serializers)
self.rend = salt.loader.render(self.opts, self.functions, states=self.states, context=self.state_con)
class MasterHighState(HighState):
'''
Execute highstate compilation from the master
'''
def __init__(self, master_opts, minion_opts, grains, id_,
saltenv=None):
# Force the fileclient to be local
opts = copy.deepcopy(minion_opts)
opts['file_client'] = 'local'
opts['file_roots'] = master_opts['master_roots']
opts['renderer'] = master_opts['renderer']
opts['state_top'] = master_opts['state_top']
opts['id'] = id_
opts['grains'] = grains
HighState.__init__(self, opts)
class RemoteHighState(object):
'''
Manage gathering the data from the master
'''
# XXX: This class doesn't seem to be used anywhere
def __init__(self, opts, grains):
self.opts = opts
self.grains = grains
self.serial = salt.payload.Serial(self.opts)
# self.auth = salt.crypt.SAuth(opts)
self.channel = salt.transport.client.ReqChannel.factory(self.opts['master_uri'])
self._closing = False
def compile_master(self):
'''
Return the state data from the master
'''
load = {'grains': self.grains,
'opts': self.opts,
'cmd': '_master_state'}
try:
return self.channel.send(load, tries=3, timeout=72000)
except SaltReqTimeoutError:
return {}
def destroy(self):
if self._closing:
return
self._closing = True
self.channel.close()
def __del__(self):
self.destroy()
|
saltstack/salt
|
salt/state.py
|
trim_req
|
python
|
def trim_req(req):
'''
Trim any function off of a requisite
'''
reqfirst = next(iter(req))
if '.' in reqfirst:
return {reqfirst.split('.')[0]: req[reqfirst]}
return req
|
Trim any function off of a requisite
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L207-L214
| null |
# -*- coding: utf-8 -*-
'''
The State Compiler is used to execute states in Salt. A state is unlike
an execution module in that instead of just executing a command, it
ensures that a certain state is present on the system.
The data sent to the state calls is as follows:
{ 'state': '<state module name>',
'fun': '<state function name>',
'name': '<the name argument passed to all states>'
'argn': '<arbitrary argument, can have many of these>'
}
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import copy
import site
import fnmatch
import logging
import datetime
import traceback
import re
import time
import random
import collections
# Import salt libs
import salt.loader
import salt.minion
import salt.pillar
import salt.fileclient
import salt.utils.args
import salt.utils.crypt
import salt.utils.data
import salt.utils.decorators.state
import salt.utils.dictupdate
import salt.utils.event
import salt.utils.files
import salt.utils.hashutils
import salt.utils.immutabletypes as immutabletypes
import salt.utils.msgpack as msgpack
import salt.utils.platform
import salt.utils.process
import salt.utils.url
import salt.syspaths as syspaths
import salt.transport.client
from salt.serializers.msgpack import serialize as msgpack_serialize, deserialize as msgpack_deserialize
from salt.template import compile_template, compile_template_str
from salt.exceptions import (
SaltRenderError,
SaltReqTimeoutError
)
from salt.utils.odict import OrderedDict, DefaultOrderedDict
# Explicit late import to avoid circular import. DO NOT MOVE THIS.
import salt.utils.yamlloader as yamlloader
# Import third party libs
# pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext import six
from salt.ext.six.moves import map, range, reload_module
# pylint: enable=import-error,no-name-in-module,redefined-builtin
log = logging.getLogger(__name__)
# These are keywords passed to state module functions which are to be used
# by salt in this state module and not on the actual state module function
STATE_REQUISITE_KEYWORDS = frozenset([
'onchanges',
'onchanges_any',
'onfail',
'onfail_any',
'onfail_all',
'onfail_stop',
'prereq',
'prerequired',
'watch',
'watch_any',
'require',
'require_any',
'listen',
])
STATE_REQUISITE_IN_KEYWORDS = frozenset([
'onchanges_in',
'onfail_in',
'prereq_in',
'watch_in',
'require_in',
'listen_in',
])
STATE_RUNTIME_KEYWORDS = frozenset([
'fun',
'state',
'check_cmd',
'failhard',
'onlyif',
'unless',
'retry',
'order',
'parallel',
'prereq',
'prereq_in',
'prerequired',
'reload_modules',
'reload_grains',
'reload_pillar',
'runas',
'runas_password',
'fire_event',
'saltenv',
'use',
'use_in',
'__env__',
'__sls__',
'__id__',
'__orchestration_jid__',
'__pub_user',
'__pub_arg',
'__pub_id',
'__pub_jid',
'__pub_fun',
'__pub_fun_args',
'__pub_schedule',
'__pub_tgt',
'__pub_ret',
'__pub_pid',
'__pub_tgt_type',
'__prereq__',
])
STATE_INTERNAL_KEYWORDS = STATE_REQUISITE_KEYWORDS.union(STATE_REQUISITE_IN_KEYWORDS).union(STATE_RUNTIME_KEYWORDS)
def _odict_hashable(self):
return id(self)
OrderedDict.__hash__ = _odict_hashable
def split_low_tag(tag):
'''
Take a low tag and split it back into the low dict that it came from
'''
state, id_, name, fun = tag.split('_|-')
return {'state': state,
'__id__': id_,
'name': name,
'fun': fun}
def _gen_tag(low):
'''
Generate the running dict tag string from the low data structure
'''
return '{0[state]}_|-{0[__id__]}_|-{0[name]}_|-{0[fun]}'.format(low)
def _clean_tag(tag):
'''
Make tag name safe for filenames
'''
return salt.utils.files.safe_filename_leaf(tag)
def _l_tag(name, id_):
low = {'name': 'listen_{0}'.format(name),
'__id__': 'listen_{0}'.format(id_),
'state': 'Listen_Error',
'fun': 'Listen_Error'}
return _gen_tag(low)
def _calculate_fake_duration():
'''
Generate a NULL duration for when states do not run
but we want the results to be consistent.
'''
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - \
(datetime.datetime.utcnow() - datetime.datetime.now())
utc_finish_time = datetime.datetime.utcnow()
start_time = local_start_time.time().isoformat()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
return start_time, duration
def get_accumulator_dir(cachedir):
'''
Return the directory that accumulator data is stored in, creating it if it
doesn't exist.
'''
fn_ = os.path.join(cachedir, 'accumulator')
if not os.path.isdir(fn_):
# accumulator_dir is not present, create it
os.makedirs(fn_)
return fn_
def state_args(id_, state, high):
'''
Return a set of the arguments passed to the named state
'''
args = set()
if id_ not in high:
return args
if state not in high[id_]:
return args
for item in high[id_][state]:
if not isinstance(item, dict):
continue
if len(item) != 1:
continue
args.add(next(iter(item)))
return args
def find_name(name, state, high):
'''
Scan high data for the id referencing the given name and return a list of (IDs, state) tuples that match
Note: if `state` is sls, then we are looking for all IDs that match the given SLS
'''
ext_id = []
if name in high:
ext_id.append((name, state))
# if we are requiring an entire SLS, then we need to add ourselves to everything in that SLS
elif state == 'sls':
for nid, item in six.iteritems(high):
if item['__sls__'] == name:
ext_id.append((nid, next(iter(item))))
# otherwise we are requiring a single state, lets find it
else:
# We need to scan for the name
for nid in high:
if state in high[nid]:
if isinstance(high[nid][state], list):
for arg in high[nid][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if arg[next(iter(arg))] == name:
ext_id.append((nid, state))
return ext_id
def find_sls_ids(sls, high):
'''
Scan for all ids in the given sls and return them in a dict; {name: state}
'''
ret = []
for nid, item in six.iteritems(high):
try:
sls_tgt = item['__sls__']
except TypeError:
if nid != '__exclude__':
log.error(
'Invalid non-dict item \'%s\' in high data. Value: %r',
nid, item
)
continue
else:
if sls_tgt == sls:
for st_ in item:
if st_.startswith('__'):
continue
ret.append((nid, st_))
return ret
def format_log(ret):
'''
Format the state into a log message
'''
msg = ''
if isinstance(ret, dict):
# Looks like the ret may be a valid state return
if 'changes' in ret:
# Yep, looks like a valid state return
chg = ret['changes']
if not chg:
if ret['comment']:
msg = ret['comment']
else:
msg = 'No changes made for {0[name]}'.format(ret)
elif isinstance(chg, dict):
if 'diff' in chg:
if isinstance(chg['diff'], six.string_types):
msg = 'File changed:\n{0}'.format(chg['diff'])
if all([isinstance(x, dict) for x in six.itervalues(chg)]):
if all([('old' in x and 'new' in x)
for x in six.itervalues(chg)]):
msg = 'Made the following changes:\n'
for pkg in chg:
old = chg[pkg]['old']
if not old and old not in (False, None):
old = 'absent'
new = chg[pkg]['new']
if not new and new not in (False, None):
new = 'absent'
# This must be able to handle unicode as some package names contain
# non-ascii characters like "Français" or "Español". See Issue #33605.
msg += '\'{0}\' changed from \'{1}\' to \'{2}\'\n'.format(pkg, old, new)
if not msg:
msg = six.text_type(ret['changes'])
if ret['result'] is True or ret['result'] is None:
log.info(msg)
else:
log.error(msg)
else:
# catch unhandled data
log.info(six.text_type(ret))
def master_compile(master_opts, minion_opts, grains, id_, saltenv):
'''
Compile the master side low state data, and build the hidden state file
'''
st_ = MasterHighState(master_opts, minion_opts, grains, id_, saltenv)
return st_.compile_highstate()
def ishashable(obj):
try:
hash(obj)
except TypeError:
return False
return True
def mock_ret(cdata):
'''
Returns a mocked return dict with information about the run, without
executing the state function
'''
# As this is expanded it should be sent into the execution module
# layer or it should be turned into a standalone loader system
if cdata['args']:
name = cdata['args'][0]
else:
name = cdata['kwargs']['name']
return {'name': name,
'comment': 'Not called, mocked',
'changes': {},
'result': True}
class StateError(Exception):
'''
Custom exception class.
'''
pass
class Compiler(object):
'''
Class used to compile and manage the High Data structure
'''
def __init__(self, opts, renderers):
self.opts = opts
self.rend = renderers
def render_template(self, template, **kwargs):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'],
**kwargs)
if not high:
return high
return self.pad_funcs(high)
def pad_funcs(self, high):
'''
Turns dot delimited function refs into function strings
'''
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state? It needs to be padded!
if '.' in high[name]:
comps = high[name].split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}'.format(
name,
body['__sls__'],
type(name).__name__
)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(('The {0}'
' statement in state \'{1}\' in SLS \'{2}\' '
'needs to be formed as a list').format(
argfirst,
name,
body['__sls__']
))
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = {'state': state}
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append((
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
))
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'is SLS {1}\n'
).format(
six.text_type(req_val),
body['__sls__']))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(('Multiple dictionaries '
'defined in argument of state \'{0}\' in SLS'
' \'{1}\'').format(
name,
body['__sls__']))
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(('No function declared in state \'{0}\' in'
' SLS \'{1}\'').format(state, body['__sls__']))
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunk['name'] = salt.utils.data.decode(chunk['name'])
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = {'state': state,
'name': name}
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
continue
else:
chunk.update(arg)
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order = name_order + 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associtaed ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if body.get('__sls__', '') in ex_sls:
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
class HighState(BaseHighState):
'''
Generate and execute the salt "High State". The High State is the
compound state derived from a group of template files stored on the
salt master or in the local cache.
'''
# a stack of active HighState objects during a state.highstate run
stack = []
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.opts = opts
self.client = salt.fileclient.get_file_client(self.opts)
BaseHighState.__init__(self, opts)
self.state = State(self.opts,
pillar_override,
jid,
pillar_enc,
proxy=proxy,
context=context,
mocked=mocked,
loader=loader,
initial_pillar=initial_pillar)
self.matchers = salt.loader.matchers(self.opts)
self.proxy = proxy
# tracks all pydsl state declarations globally across sls files
self._pydsl_all_decls = {}
# a stack of current rendering Sls objects, maintained and used by the pydsl renderer.
self._pydsl_render_stack = []
def push_active(self):
self.stack.append(self)
@classmethod
def clear_active(cls):
# Nuclear option
#
# Blow away the entire stack. Used primarily by the test runner but also
# useful in custom wrappers of the HighState class, to reset the stack
# to a fresh state.
cls.stack = []
@classmethod
def pop_active(cls):
cls.stack.pop()
@classmethod
def get_active(cls):
try:
return cls.stack[-1]
except IndexError:
return None
class MasterState(State):
'''
Create a State object for master side compiling
'''
def __init__(self, opts, minion):
State.__init__(self, opts)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
# Load a modified client interface that looks like the interface used
# from the minion, but uses remote execution
#
self.functions = salt.client.FunctionWrapper(
self.opts,
self.opts['id']
)
# Load the states, but they should not be used in this class apart
# from inspection
self.utils = salt.loader.utils(self.opts)
self.serializers = salt.loader.serializers(self.opts)
self.states = salt.loader.states(self.opts, self.functions, self.utils, self.serializers)
self.rend = salt.loader.render(self.opts, self.functions, states=self.states, context=self.state_con)
class MasterHighState(HighState):
'''
Execute highstate compilation from the master
'''
def __init__(self, master_opts, minion_opts, grains, id_,
saltenv=None):
# Force the fileclient to be local
opts = copy.deepcopy(minion_opts)
opts['file_client'] = 'local'
opts['file_roots'] = master_opts['master_roots']
opts['renderer'] = master_opts['renderer']
opts['state_top'] = master_opts['state_top']
opts['id'] = id_
opts['grains'] = grains
HighState.__init__(self, opts)
class RemoteHighState(object):
'''
Manage gathering the data from the master
'''
# XXX: This class doesn't seem to be used anywhere
def __init__(self, opts, grains):
self.opts = opts
self.grains = grains
self.serial = salt.payload.Serial(self.opts)
# self.auth = salt.crypt.SAuth(opts)
self.channel = salt.transport.client.ReqChannel.factory(self.opts['master_uri'])
self._closing = False
def compile_master(self):
'''
Return the state data from the master
'''
load = {'grains': self.grains,
'opts': self.opts,
'cmd': '_master_state'}
try:
return self.channel.send(load, tries=3, timeout=72000)
except SaltReqTimeoutError:
return {}
def destroy(self):
if self._closing:
return
self._closing = True
self.channel.close()
def __del__(self):
self.destroy()
|
saltstack/salt
|
salt/state.py
|
state_args
|
python
|
def state_args(id_, state, high):
'''
Return a set of the arguments passed to the named state
'''
args = set()
if id_ not in high:
return args
if state not in high[id_]:
return args
for item in high[id_][state]:
if not isinstance(item, dict):
continue
if len(item) != 1:
continue
args.add(next(iter(item)))
return args
|
Return a set of the arguments passed to the named state
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L217-L232
| null |
# -*- coding: utf-8 -*-
'''
The State Compiler is used to execute states in Salt. A state is unlike
an execution module in that instead of just executing a command, it
ensures that a certain state is present on the system.
The data sent to the state calls is as follows:
{ 'state': '<state module name>',
'fun': '<state function name>',
'name': '<the name argument passed to all states>'
'argn': '<arbitrary argument, can have many of these>'
}
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import copy
import site
import fnmatch
import logging
import datetime
import traceback
import re
import time
import random
import collections
# Import salt libs
import salt.loader
import salt.minion
import salt.pillar
import salt.fileclient
import salt.utils.args
import salt.utils.crypt
import salt.utils.data
import salt.utils.decorators.state
import salt.utils.dictupdate
import salt.utils.event
import salt.utils.files
import salt.utils.hashutils
import salt.utils.immutabletypes as immutabletypes
import salt.utils.msgpack as msgpack
import salt.utils.platform
import salt.utils.process
import salt.utils.url
import salt.syspaths as syspaths
import salt.transport.client
from salt.serializers.msgpack import serialize as msgpack_serialize, deserialize as msgpack_deserialize
from salt.template import compile_template, compile_template_str
from salt.exceptions import (
SaltRenderError,
SaltReqTimeoutError
)
from salt.utils.odict import OrderedDict, DefaultOrderedDict
# Explicit late import to avoid circular import. DO NOT MOVE THIS.
import salt.utils.yamlloader as yamlloader
# Import third party libs
# pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext import six
from salt.ext.six.moves import map, range, reload_module
# pylint: enable=import-error,no-name-in-module,redefined-builtin
log = logging.getLogger(__name__)
# These are keywords passed to state module functions which are to be used
# by salt in this state module and not on the actual state module function
STATE_REQUISITE_KEYWORDS = frozenset([
'onchanges',
'onchanges_any',
'onfail',
'onfail_any',
'onfail_all',
'onfail_stop',
'prereq',
'prerequired',
'watch',
'watch_any',
'require',
'require_any',
'listen',
])
STATE_REQUISITE_IN_KEYWORDS = frozenset([
'onchanges_in',
'onfail_in',
'prereq_in',
'watch_in',
'require_in',
'listen_in',
])
STATE_RUNTIME_KEYWORDS = frozenset([
'fun',
'state',
'check_cmd',
'failhard',
'onlyif',
'unless',
'retry',
'order',
'parallel',
'prereq',
'prereq_in',
'prerequired',
'reload_modules',
'reload_grains',
'reload_pillar',
'runas',
'runas_password',
'fire_event',
'saltenv',
'use',
'use_in',
'__env__',
'__sls__',
'__id__',
'__orchestration_jid__',
'__pub_user',
'__pub_arg',
'__pub_id',
'__pub_jid',
'__pub_fun',
'__pub_fun_args',
'__pub_schedule',
'__pub_tgt',
'__pub_ret',
'__pub_pid',
'__pub_tgt_type',
'__prereq__',
])
STATE_INTERNAL_KEYWORDS = STATE_REQUISITE_KEYWORDS.union(STATE_REQUISITE_IN_KEYWORDS).union(STATE_RUNTIME_KEYWORDS)
def _odict_hashable(self):
return id(self)
OrderedDict.__hash__ = _odict_hashable
def split_low_tag(tag):
'''
Take a low tag and split it back into the low dict that it came from
'''
state, id_, name, fun = tag.split('_|-')
return {'state': state,
'__id__': id_,
'name': name,
'fun': fun}
def _gen_tag(low):
'''
Generate the running dict tag string from the low data structure
'''
return '{0[state]}_|-{0[__id__]}_|-{0[name]}_|-{0[fun]}'.format(low)
def _clean_tag(tag):
'''
Make tag name safe for filenames
'''
return salt.utils.files.safe_filename_leaf(tag)
def _l_tag(name, id_):
low = {'name': 'listen_{0}'.format(name),
'__id__': 'listen_{0}'.format(id_),
'state': 'Listen_Error',
'fun': 'Listen_Error'}
return _gen_tag(low)
def _calculate_fake_duration():
'''
Generate a NULL duration for when states do not run
but we want the results to be consistent.
'''
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - \
(datetime.datetime.utcnow() - datetime.datetime.now())
utc_finish_time = datetime.datetime.utcnow()
start_time = local_start_time.time().isoformat()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
return start_time, duration
def get_accumulator_dir(cachedir):
'''
Return the directory that accumulator data is stored in, creating it if it
doesn't exist.
'''
fn_ = os.path.join(cachedir, 'accumulator')
if not os.path.isdir(fn_):
# accumulator_dir is not present, create it
os.makedirs(fn_)
return fn_
def trim_req(req):
'''
Trim any function off of a requisite
'''
reqfirst = next(iter(req))
if '.' in reqfirst:
return {reqfirst.split('.')[0]: req[reqfirst]}
return req
def find_name(name, state, high):
'''
Scan high data for the id referencing the given name and return a list of (IDs, state) tuples that match
Note: if `state` is sls, then we are looking for all IDs that match the given SLS
'''
ext_id = []
if name in high:
ext_id.append((name, state))
# if we are requiring an entire SLS, then we need to add ourselves to everything in that SLS
elif state == 'sls':
for nid, item in six.iteritems(high):
if item['__sls__'] == name:
ext_id.append((nid, next(iter(item))))
# otherwise we are requiring a single state, lets find it
else:
# We need to scan for the name
for nid in high:
if state in high[nid]:
if isinstance(high[nid][state], list):
for arg in high[nid][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if arg[next(iter(arg))] == name:
ext_id.append((nid, state))
return ext_id
def find_sls_ids(sls, high):
'''
Scan for all ids in the given sls and return them in a dict; {name: state}
'''
ret = []
for nid, item in six.iteritems(high):
try:
sls_tgt = item['__sls__']
except TypeError:
if nid != '__exclude__':
log.error(
'Invalid non-dict item \'%s\' in high data. Value: %r',
nid, item
)
continue
else:
if sls_tgt == sls:
for st_ in item:
if st_.startswith('__'):
continue
ret.append((nid, st_))
return ret
def format_log(ret):
'''
Format the state into a log message
'''
msg = ''
if isinstance(ret, dict):
# Looks like the ret may be a valid state return
if 'changes' in ret:
# Yep, looks like a valid state return
chg = ret['changes']
if not chg:
if ret['comment']:
msg = ret['comment']
else:
msg = 'No changes made for {0[name]}'.format(ret)
elif isinstance(chg, dict):
if 'diff' in chg:
if isinstance(chg['diff'], six.string_types):
msg = 'File changed:\n{0}'.format(chg['diff'])
if all([isinstance(x, dict) for x in six.itervalues(chg)]):
if all([('old' in x and 'new' in x)
for x in six.itervalues(chg)]):
msg = 'Made the following changes:\n'
for pkg in chg:
old = chg[pkg]['old']
if not old and old not in (False, None):
old = 'absent'
new = chg[pkg]['new']
if not new and new not in (False, None):
new = 'absent'
# This must be able to handle unicode as some package names contain
# non-ascii characters like "Français" or "Español". See Issue #33605.
msg += '\'{0}\' changed from \'{1}\' to \'{2}\'\n'.format(pkg, old, new)
if not msg:
msg = six.text_type(ret['changes'])
if ret['result'] is True or ret['result'] is None:
log.info(msg)
else:
log.error(msg)
else:
# catch unhandled data
log.info(six.text_type(ret))
def master_compile(master_opts, minion_opts, grains, id_, saltenv):
'''
Compile the master side low state data, and build the hidden state file
'''
st_ = MasterHighState(master_opts, minion_opts, grains, id_, saltenv)
return st_.compile_highstate()
def ishashable(obj):
try:
hash(obj)
except TypeError:
return False
return True
def mock_ret(cdata):
'''
Returns a mocked return dict with information about the run, without
executing the state function
'''
# As this is expanded it should be sent into the execution module
# layer or it should be turned into a standalone loader system
if cdata['args']:
name = cdata['args'][0]
else:
name = cdata['kwargs']['name']
return {'name': name,
'comment': 'Not called, mocked',
'changes': {},
'result': True}
class StateError(Exception):
'''
Custom exception class.
'''
pass
class Compiler(object):
'''
Class used to compile and manage the High Data structure
'''
def __init__(self, opts, renderers):
self.opts = opts
self.rend = renderers
def render_template(self, template, **kwargs):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'],
**kwargs)
if not high:
return high
return self.pad_funcs(high)
def pad_funcs(self, high):
'''
Turns dot delimited function refs into function strings
'''
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state? It needs to be padded!
if '.' in high[name]:
comps = high[name].split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}'.format(
name,
body['__sls__'],
type(name).__name__
)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(('The {0}'
' statement in state \'{1}\' in SLS \'{2}\' '
'needs to be formed as a list').format(
argfirst,
name,
body['__sls__']
))
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = {'state': state}
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append((
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
))
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'is SLS {1}\n'
).format(
six.text_type(req_val),
body['__sls__']))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(('Multiple dictionaries '
'defined in argument of state \'{0}\' in SLS'
' \'{1}\'').format(
name,
body['__sls__']))
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(('No function declared in state \'{0}\' in'
' SLS \'{1}\'').format(state, body['__sls__']))
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunk['name'] = salt.utils.data.decode(chunk['name'])
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = {'state': state,
'name': name}
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
continue
else:
chunk.update(arg)
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order = name_order + 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associtaed ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if body.get('__sls__', '') in ex_sls:
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
class HighState(BaseHighState):
'''
Generate and execute the salt "High State". The High State is the
compound state derived from a group of template files stored on the
salt master or in the local cache.
'''
# a stack of active HighState objects during a state.highstate run
stack = []
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.opts = opts
self.client = salt.fileclient.get_file_client(self.opts)
BaseHighState.__init__(self, opts)
self.state = State(self.opts,
pillar_override,
jid,
pillar_enc,
proxy=proxy,
context=context,
mocked=mocked,
loader=loader,
initial_pillar=initial_pillar)
self.matchers = salt.loader.matchers(self.opts)
self.proxy = proxy
# tracks all pydsl state declarations globally across sls files
self._pydsl_all_decls = {}
# a stack of current rendering Sls objects, maintained and used by the pydsl renderer.
self._pydsl_render_stack = []
def push_active(self):
self.stack.append(self)
@classmethod
def clear_active(cls):
# Nuclear option
#
# Blow away the entire stack. Used primarily by the test runner but also
# useful in custom wrappers of the HighState class, to reset the stack
# to a fresh state.
cls.stack = []
@classmethod
def pop_active(cls):
cls.stack.pop()
@classmethod
def get_active(cls):
try:
return cls.stack[-1]
except IndexError:
return None
class MasterState(State):
'''
Create a State object for master side compiling
'''
def __init__(self, opts, minion):
State.__init__(self, opts)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
# Load a modified client interface that looks like the interface used
# from the minion, but uses remote execution
#
self.functions = salt.client.FunctionWrapper(
self.opts,
self.opts['id']
)
# Load the states, but they should not be used in this class apart
# from inspection
self.utils = salt.loader.utils(self.opts)
self.serializers = salt.loader.serializers(self.opts)
self.states = salt.loader.states(self.opts, self.functions, self.utils, self.serializers)
self.rend = salt.loader.render(self.opts, self.functions, states=self.states, context=self.state_con)
class MasterHighState(HighState):
'''
Execute highstate compilation from the master
'''
def __init__(self, master_opts, minion_opts, grains, id_,
saltenv=None):
# Force the fileclient to be local
opts = copy.deepcopy(minion_opts)
opts['file_client'] = 'local'
opts['file_roots'] = master_opts['master_roots']
opts['renderer'] = master_opts['renderer']
opts['state_top'] = master_opts['state_top']
opts['id'] = id_
opts['grains'] = grains
HighState.__init__(self, opts)
class RemoteHighState(object):
'''
Manage gathering the data from the master
'''
# XXX: This class doesn't seem to be used anywhere
def __init__(self, opts, grains):
self.opts = opts
self.grains = grains
self.serial = salt.payload.Serial(self.opts)
# self.auth = salt.crypt.SAuth(opts)
self.channel = salt.transport.client.ReqChannel.factory(self.opts['master_uri'])
self._closing = False
def compile_master(self):
'''
Return the state data from the master
'''
load = {'grains': self.grains,
'opts': self.opts,
'cmd': '_master_state'}
try:
return self.channel.send(load, tries=3, timeout=72000)
except SaltReqTimeoutError:
return {}
def destroy(self):
if self._closing:
return
self._closing = True
self.channel.close()
def __del__(self):
self.destroy()
|
saltstack/salt
|
salt/state.py
|
find_name
|
python
|
def find_name(name, state, high):
'''
Scan high data for the id referencing the given name and return a list of (IDs, state) tuples that match
Note: if `state` is sls, then we are looking for all IDs that match the given SLS
'''
ext_id = []
if name in high:
ext_id.append((name, state))
# if we are requiring an entire SLS, then we need to add ourselves to everything in that SLS
elif state == 'sls':
for nid, item in six.iteritems(high):
if item['__sls__'] == name:
ext_id.append((nid, next(iter(item))))
# otherwise we are requiring a single state, lets find it
else:
# We need to scan for the name
for nid in high:
if state in high[nid]:
if isinstance(high[nid][state], list):
for arg in high[nid][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if arg[next(iter(arg))] == name:
ext_id.append((nid, state))
return ext_id
|
Scan high data for the id referencing the given name and return a list of (IDs, state) tuples that match
Note: if `state` is sls, then we are looking for all IDs that match the given SLS
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L235-L262
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n"
] |
# -*- coding: utf-8 -*-
'''
The State Compiler is used to execute states in Salt. A state is unlike
an execution module in that instead of just executing a command, it
ensures that a certain state is present on the system.
The data sent to the state calls is as follows:
{ 'state': '<state module name>',
'fun': '<state function name>',
'name': '<the name argument passed to all states>'
'argn': '<arbitrary argument, can have many of these>'
}
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import copy
import site
import fnmatch
import logging
import datetime
import traceback
import re
import time
import random
import collections
# Import salt libs
import salt.loader
import salt.minion
import salt.pillar
import salt.fileclient
import salt.utils.args
import salt.utils.crypt
import salt.utils.data
import salt.utils.decorators.state
import salt.utils.dictupdate
import salt.utils.event
import salt.utils.files
import salt.utils.hashutils
import salt.utils.immutabletypes as immutabletypes
import salt.utils.msgpack as msgpack
import salt.utils.platform
import salt.utils.process
import salt.utils.url
import salt.syspaths as syspaths
import salt.transport.client
from salt.serializers.msgpack import serialize as msgpack_serialize, deserialize as msgpack_deserialize
from salt.template import compile_template, compile_template_str
from salt.exceptions import (
SaltRenderError,
SaltReqTimeoutError
)
from salt.utils.odict import OrderedDict, DefaultOrderedDict
# Explicit late import to avoid circular import. DO NOT MOVE THIS.
import salt.utils.yamlloader as yamlloader
# Import third party libs
# pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext import six
from salt.ext.six.moves import map, range, reload_module
# pylint: enable=import-error,no-name-in-module,redefined-builtin
log = logging.getLogger(__name__)
# These are keywords passed to state module functions which are to be used
# by salt in this state module and not on the actual state module function
STATE_REQUISITE_KEYWORDS = frozenset([
'onchanges',
'onchanges_any',
'onfail',
'onfail_any',
'onfail_all',
'onfail_stop',
'prereq',
'prerequired',
'watch',
'watch_any',
'require',
'require_any',
'listen',
])
STATE_REQUISITE_IN_KEYWORDS = frozenset([
'onchanges_in',
'onfail_in',
'prereq_in',
'watch_in',
'require_in',
'listen_in',
])
STATE_RUNTIME_KEYWORDS = frozenset([
'fun',
'state',
'check_cmd',
'failhard',
'onlyif',
'unless',
'retry',
'order',
'parallel',
'prereq',
'prereq_in',
'prerequired',
'reload_modules',
'reload_grains',
'reload_pillar',
'runas',
'runas_password',
'fire_event',
'saltenv',
'use',
'use_in',
'__env__',
'__sls__',
'__id__',
'__orchestration_jid__',
'__pub_user',
'__pub_arg',
'__pub_id',
'__pub_jid',
'__pub_fun',
'__pub_fun_args',
'__pub_schedule',
'__pub_tgt',
'__pub_ret',
'__pub_pid',
'__pub_tgt_type',
'__prereq__',
])
STATE_INTERNAL_KEYWORDS = STATE_REQUISITE_KEYWORDS.union(STATE_REQUISITE_IN_KEYWORDS).union(STATE_RUNTIME_KEYWORDS)
def _odict_hashable(self):
return id(self)
OrderedDict.__hash__ = _odict_hashable
def split_low_tag(tag):
'''
Take a low tag and split it back into the low dict that it came from
'''
state, id_, name, fun = tag.split('_|-')
return {'state': state,
'__id__': id_,
'name': name,
'fun': fun}
def _gen_tag(low):
'''
Generate the running dict tag string from the low data structure
'''
return '{0[state]}_|-{0[__id__]}_|-{0[name]}_|-{0[fun]}'.format(low)
def _clean_tag(tag):
'''
Make tag name safe for filenames
'''
return salt.utils.files.safe_filename_leaf(tag)
def _l_tag(name, id_):
low = {'name': 'listen_{0}'.format(name),
'__id__': 'listen_{0}'.format(id_),
'state': 'Listen_Error',
'fun': 'Listen_Error'}
return _gen_tag(low)
def _calculate_fake_duration():
'''
Generate a NULL duration for when states do not run
but we want the results to be consistent.
'''
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - \
(datetime.datetime.utcnow() - datetime.datetime.now())
utc_finish_time = datetime.datetime.utcnow()
start_time = local_start_time.time().isoformat()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
return start_time, duration
def get_accumulator_dir(cachedir):
'''
Return the directory that accumulator data is stored in, creating it if it
doesn't exist.
'''
fn_ = os.path.join(cachedir, 'accumulator')
if not os.path.isdir(fn_):
# accumulator_dir is not present, create it
os.makedirs(fn_)
return fn_
def trim_req(req):
'''
Trim any function off of a requisite
'''
reqfirst = next(iter(req))
if '.' in reqfirst:
return {reqfirst.split('.')[0]: req[reqfirst]}
return req
def state_args(id_, state, high):
'''
Return a set of the arguments passed to the named state
'''
args = set()
if id_ not in high:
return args
if state not in high[id_]:
return args
for item in high[id_][state]:
if not isinstance(item, dict):
continue
if len(item) != 1:
continue
args.add(next(iter(item)))
return args
def find_sls_ids(sls, high):
'''
Scan for all ids in the given sls and return them in a dict; {name: state}
'''
ret = []
for nid, item in six.iteritems(high):
try:
sls_tgt = item['__sls__']
except TypeError:
if nid != '__exclude__':
log.error(
'Invalid non-dict item \'%s\' in high data. Value: %r',
nid, item
)
continue
else:
if sls_tgt == sls:
for st_ in item:
if st_.startswith('__'):
continue
ret.append((nid, st_))
return ret
def format_log(ret):
'''
Format the state into a log message
'''
msg = ''
if isinstance(ret, dict):
# Looks like the ret may be a valid state return
if 'changes' in ret:
# Yep, looks like a valid state return
chg = ret['changes']
if not chg:
if ret['comment']:
msg = ret['comment']
else:
msg = 'No changes made for {0[name]}'.format(ret)
elif isinstance(chg, dict):
if 'diff' in chg:
if isinstance(chg['diff'], six.string_types):
msg = 'File changed:\n{0}'.format(chg['diff'])
if all([isinstance(x, dict) for x in six.itervalues(chg)]):
if all([('old' in x and 'new' in x)
for x in six.itervalues(chg)]):
msg = 'Made the following changes:\n'
for pkg in chg:
old = chg[pkg]['old']
if not old and old not in (False, None):
old = 'absent'
new = chg[pkg]['new']
if not new and new not in (False, None):
new = 'absent'
# This must be able to handle unicode as some package names contain
# non-ascii characters like "Français" or "Español". See Issue #33605.
msg += '\'{0}\' changed from \'{1}\' to \'{2}\'\n'.format(pkg, old, new)
if not msg:
msg = six.text_type(ret['changes'])
if ret['result'] is True or ret['result'] is None:
log.info(msg)
else:
log.error(msg)
else:
# catch unhandled data
log.info(six.text_type(ret))
def master_compile(master_opts, minion_opts, grains, id_, saltenv):
'''
Compile the master side low state data, and build the hidden state file
'''
st_ = MasterHighState(master_opts, minion_opts, grains, id_, saltenv)
return st_.compile_highstate()
def ishashable(obj):
try:
hash(obj)
except TypeError:
return False
return True
def mock_ret(cdata):
'''
Returns a mocked return dict with information about the run, without
executing the state function
'''
# As this is expanded it should be sent into the execution module
# layer or it should be turned into a standalone loader system
if cdata['args']:
name = cdata['args'][0]
else:
name = cdata['kwargs']['name']
return {'name': name,
'comment': 'Not called, mocked',
'changes': {},
'result': True}
class StateError(Exception):
'''
Custom exception class.
'''
pass
class Compiler(object):
'''
Class used to compile and manage the High Data structure
'''
def __init__(self, opts, renderers):
self.opts = opts
self.rend = renderers
def render_template(self, template, **kwargs):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'],
**kwargs)
if not high:
return high
return self.pad_funcs(high)
def pad_funcs(self, high):
'''
Turns dot delimited function refs into function strings
'''
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state? It needs to be padded!
if '.' in high[name]:
comps = high[name].split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}'.format(
name,
body['__sls__'],
type(name).__name__
)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(('The {0}'
' statement in state \'{1}\' in SLS \'{2}\' '
'needs to be formed as a list').format(
argfirst,
name,
body['__sls__']
))
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = {'state': state}
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append((
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
))
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'is SLS {1}\n'
).format(
six.text_type(req_val),
body['__sls__']))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(('Multiple dictionaries '
'defined in argument of state \'{0}\' in SLS'
' \'{1}\'').format(
name,
body['__sls__']))
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(('No function declared in state \'{0}\' in'
' SLS \'{1}\'').format(state, body['__sls__']))
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunk['name'] = salt.utils.data.decode(chunk['name'])
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = {'state': state,
'name': name}
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
continue
else:
chunk.update(arg)
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order = name_order + 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associtaed ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if body.get('__sls__', '') in ex_sls:
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
class HighState(BaseHighState):
'''
Generate and execute the salt "High State". The High State is the
compound state derived from a group of template files stored on the
salt master or in the local cache.
'''
# a stack of active HighState objects during a state.highstate run
stack = []
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.opts = opts
self.client = salt.fileclient.get_file_client(self.opts)
BaseHighState.__init__(self, opts)
self.state = State(self.opts,
pillar_override,
jid,
pillar_enc,
proxy=proxy,
context=context,
mocked=mocked,
loader=loader,
initial_pillar=initial_pillar)
self.matchers = salt.loader.matchers(self.opts)
self.proxy = proxy
# tracks all pydsl state declarations globally across sls files
self._pydsl_all_decls = {}
# a stack of current rendering Sls objects, maintained and used by the pydsl renderer.
self._pydsl_render_stack = []
def push_active(self):
self.stack.append(self)
@classmethod
def clear_active(cls):
# Nuclear option
#
# Blow away the entire stack. Used primarily by the test runner but also
# useful in custom wrappers of the HighState class, to reset the stack
# to a fresh state.
cls.stack = []
@classmethod
def pop_active(cls):
cls.stack.pop()
@classmethod
def get_active(cls):
try:
return cls.stack[-1]
except IndexError:
return None
class MasterState(State):
'''
Create a State object for master side compiling
'''
def __init__(self, opts, minion):
State.__init__(self, opts)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
# Load a modified client interface that looks like the interface used
# from the minion, but uses remote execution
#
self.functions = salt.client.FunctionWrapper(
self.opts,
self.opts['id']
)
# Load the states, but they should not be used in this class apart
# from inspection
self.utils = salt.loader.utils(self.opts)
self.serializers = salt.loader.serializers(self.opts)
self.states = salt.loader.states(self.opts, self.functions, self.utils, self.serializers)
self.rend = salt.loader.render(self.opts, self.functions, states=self.states, context=self.state_con)
class MasterHighState(HighState):
'''
Execute highstate compilation from the master
'''
def __init__(self, master_opts, minion_opts, grains, id_,
saltenv=None):
# Force the fileclient to be local
opts = copy.deepcopy(minion_opts)
opts['file_client'] = 'local'
opts['file_roots'] = master_opts['master_roots']
opts['renderer'] = master_opts['renderer']
opts['state_top'] = master_opts['state_top']
opts['id'] = id_
opts['grains'] = grains
HighState.__init__(self, opts)
class RemoteHighState(object):
'''
Manage gathering the data from the master
'''
# XXX: This class doesn't seem to be used anywhere
def __init__(self, opts, grains):
self.opts = opts
self.grains = grains
self.serial = salt.payload.Serial(self.opts)
# self.auth = salt.crypt.SAuth(opts)
self.channel = salt.transport.client.ReqChannel.factory(self.opts['master_uri'])
self._closing = False
def compile_master(self):
'''
Return the state data from the master
'''
load = {'grains': self.grains,
'opts': self.opts,
'cmd': '_master_state'}
try:
return self.channel.send(load, tries=3, timeout=72000)
except SaltReqTimeoutError:
return {}
def destroy(self):
if self._closing:
return
self._closing = True
self.channel.close()
def __del__(self):
self.destroy()
|
saltstack/salt
|
salt/state.py
|
find_sls_ids
|
python
|
def find_sls_ids(sls, high):
'''
Scan for all ids in the given sls and return them in a dict; {name: state}
'''
ret = []
for nid, item in six.iteritems(high):
try:
sls_tgt = item['__sls__']
except TypeError:
if nid != '__exclude__':
log.error(
'Invalid non-dict item \'%s\' in high data. Value: %r',
nid, item
)
continue
else:
if sls_tgt == sls:
for st_ in item:
if st_.startswith('__'):
continue
ret.append((nid, st_))
return ret
|
Scan for all ids in the given sls and return them in a dict; {name: state}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L265-L286
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n"
] |
# -*- coding: utf-8 -*-
'''
The State Compiler is used to execute states in Salt. A state is unlike
an execution module in that instead of just executing a command, it
ensures that a certain state is present on the system.
The data sent to the state calls is as follows:
{ 'state': '<state module name>',
'fun': '<state function name>',
'name': '<the name argument passed to all states>'
'argn': '<arbitrary argument, can have many of these>'
}
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import copy
import site
import fnmatch
import logging
import datetime
import traceback
import re
import time
import random
import collections
# Import salt libs
import salt.loader
import salt.minion
import salt.pillar
import salt.fileclient
import salt.utils.args
import salt.utils.crypt
import salt.utils.data
import salt.utils.decorators.state
import salt.utils.dictupdate
import salt.utils.event
import salt.utils.files
import salt.utils.hashutils
import salt.utils.immutabletypes as immutabletypes
import salt.utils.msgpack as msgpack
import salt.utils.platform
import salt.utils.process
import salt.utils.url
import salt.syspaths as syspaths
import salt.transport.client
from salt.serializers.msgpack import serialize as msgpack_serialize, deserialize as msgpack_deserialize
from salt.template import compile_template, compile_template_str
from salt.exceptions import (
SaltRenderError,
SaltReqTimeoutError
)
from salt.utils.odict import OrderedDict, DefaultOrderedDict
# Explicit late import to avoid circular import. DO NOT MOVE THIS.
import salt.utils.yamlloader as yamlloader
# Import third party libs
# pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext import six
from salt.ext.six.moves import map, range, reload_module
# pylint: enable=import-error,no-name-in-module,redefined-builtin
log = logging.getLogger(__name__)
# These are keywords passed to state module functions which are to be used
# by salt in this state module and not on the actual state module function
STATE_REQUISITE_KEYWORDS = frozenset([
'onchanges',
'onchanges_any',
'onfail',
'onfail_any',
'onfail_all',
'onfail_stop',
'prereq',
'prerequired',
'watch',
'watch_any',
'require',
'require_any',
'listen',
])
STATE_REQUISITE_IN_KEYWORDS = frozenset([
'onchanges_in',
'onfail_in',
'prereq_in',
'watch_in',
'require_in',
'listen_in',
])
STATE_RUNTIME_KEYWORDS = frozenset([
'fun',
'state',
'check_cmd',
'failhard',
'onlyif',
'unless',
'retry',
'order',
'parallel',
'prereq',
'prereq_in',
'prerequired',
'reload_modules',
'reload_grains',
'reload_pillar',
'runas',
'runas_password',
'fire_event',
'saltenv',
'use',
'use_in',
'__env__',
'__sls__',
'__id__',
'__orchestration_jid__',
'__pub_user',
'__pub_arg',
'__pub_id',
'__pub_jid',
'__pub_fun',
'__pub_fun_args',
'__pub_schedule',
'__pub_tgt',
'__pub_ret',
'__pub_pid',
'__pub_tgt_type',
'__prereq__',
])
STATE_INTERNAL_KEYWORDS = STATE_REQUISITE_KEYWORDS.union(STATE_REQUISITE_IN_KEYWORDS).union(STATE_RUNTIME_KEYWORDS)
def _odict_hashable(self):
return id(self)
OrderedDict.__hash__ = _odict_hashable
def split_low_tag(tag):
'''
Take a low tag and split it back into the low dict that it came from
'''
state, id_, name, fun = tag.split('_|-')
return {'state': state,
'__id__': id_,
'name': name,
'fun': fun}
def _gen_tag(low):
'''
Generate the running dict tag string from the low data structure
'''
return '{0[state]}_|-{0[__id__]}_|-{0[name]}_|-{0[fun]}'.format(low)
def _clean_tag(tag):
'''
Make tag name safe for filenames
'''
return salt.utils.files.safe_filename_leaf(tag)
def _l_tag(name, id_):
low = {'name': 'listen_{0}'.format(name),
'__id__': 'listen_{0}'.format(id_),
'state': 'Listen_Error',
'fun': 'Listen_Error'}
return _gen_tag(low)
def _calculate_fake_duration():
'''
Generate a NULL duration for when states do not run
but we want the results to be consistent.
'''
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - \
(datetime.datetime.utcnow() - datetime.datetime.now())
utc_finish_time = datetime.datetime.utcnow()
start_time = local_start_time.time().isoformat()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
return start_time, duration
def get_accumulator_dir(cachedir):
'''
Return the directory that accumulator data is stored in, creating it if it
doesn't exist.
'''
fn_ = os.path.join(cachedir, 'accumulator')
if not os.path.isdir(fn_):
# accumulator_dir is not present, create it
os.makedirs(fn_)
return fn_
def trim_req(req):
'''
Trim any function off of a requisite
'''
reqfirst = next(iter(req))
if '.' in reqfirst:
return {reqfirst.split('.')[0]: req[reqfirst]}
return req
def state_args(id_, state, high):
'''
Return a set of the arguments passed to the named state
'''
args = set()
if id_ not in high:
return args
if state not in high[id_]:
return args
for item in high[id_][state]:
if not isinstance(item, dict):
continue
if len(item) != 1:
continue
args.add(next(iter(item)))
return args
def find_name(name, state, high):
'''
Scan high data for the id referencing the given name and return a list of (IDs, state) tuples that match
Note: if `state` is sls, then we are looking for all IDs that match the given SLS
'''
ext_id = []
if name in high:
ext_id.append((name, state))
# if we are requiring an entire SLS, then we need to add ourselves to everything in that SLS
elif state == 'sls':
for nid, item in six.iteritems(high):
if item['__sls__'] == name:
ext_id.append((nid, next(iter(item))))
# otherwise we are requiring a single state, lets find it
else:
# We need to scan for the name
for nid in high:
if state in high[nid]:
if isinstance(high[nid][state], list):
for arg in high[nid][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if arg[next(iter(arg))] == name:
ext_id.append((nid, state))
return ext_id
def format_log(ret):
'''
Format the state into a log message
'''
msg = ''
if isinstance(ret, dict):
# Looks like the ret may be a valid state return
if 'changes' in ret:
# Yep, looks like a valid state return
chg = ret['changes']
if not chg:
if ret['comment']:
msg = ret['comment']
else:
msg = 'No changes made for {0[name]}'.format(ret)
elif isinstance(chg, dict):
if 'diff' in chg:
if isinstance(chg['diff'], six.string_types):
msg = 'File changed:\n{0}'.format(chg['diff'])
if all([isinstance(x, dict) for x in six.itervalues(chg)]):
if all([('old' in x and 'new' in x)
for x in six.itervalues(chg)]):
msg = 'Made the following changes:\n'
for pkg in chg:
old = chg[pkg]['old']
if not old and old not in (False, None):
old = 'absent'
new = chg[pkg]['new']
if not new and new not in (False, None):
new = 'absent'
# This must be able to handle unicode as some package names contain
# non-ascii characters like "Français" or "Español". See Issue #33605.
msg += '\'{0}\' changed from \'{1}\' to \'{2}\'\n'.format(pkg, old, new)
if not msg:
msg = six.text_type(ret['changes'])
if ret['result'] is True or ret['result'] is None:
log.info(msg)
else:
log.error(msg)
else:
# catch unhandled data
log.info(six.text_type(ret))
def master_compile(master_opts, minion_opts, grains, id_, saltenv):
'''
Compile the master side low state data, and build the hidden state file
'''
st_ = MasterHighState(master_opts, minion_opts, grains, id_, saltenv)
return st_.compile_highstate()
def ishashable(obj):
try:
hash(obj)
except TypeError:
return False
return True
def mock_ret(cdata):
'''
Returns a mocked return dict with information about the run, without
executing the state function
'''
# As this is expanded it should be sent into the execution module
# layer or it should be turned into a standalone loader system
if cdata['args']:
name = cdata['args'][0]
else:
name = cdata['kwargs']['name']
return {'name': name,
'comment': 'Not called, mocked',
'changes': {},
'result': True}
class StateError(Exception):
'''
Custom exception class.
'''
pass
class Compiler(object):
'''
Class used to compile and manage the High Data structure
'''
def __init__(self, opts, renderers):
self.opts = opts
self.rend = renderers
def render_template(self, template, **kwargs):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'],
**kwargs)
if not high:
return high
return self.pad_funcs(high)
def pad_funcs(self, high):
'''
Turns dot delimited function refs into function strings
'''
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state? It needs to be padded!
if '.' in high[name]:
comps = high[name].split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}'.format(
name,
body['__sls__'],
type(name).__name__
)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(('The {0}'
' statement in state \'{1}\' in SLS \'{2}\' '
'needs to be formed as a list').format(
argfirst,
name,
body['__sls__']
))
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = {'state': state}
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append((
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
))
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'is SLS {1}\n'
).format(
six.text_type(req_val),
body['__sls__']))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(('Multiple dictionaries '
'defined in argument of state \'{0}\' in SLS'
' \'{1}\'').format(
name,
body['__sls__']))
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(('No function declared in state \'{0}\' in'
' SLS \'{1}\'').format(state, body['__sls__']))
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunk['name'] = salt.utils.data.decode(chunk['name'])
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = {'state': state,
'name': name}
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
continue
else:
chunk.update(arg)
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order = name_order + 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associtaed ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if body.get('__sls__', '') in ex_sls:
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
class HighState(BaseHighState):
'''
Generate and execute the salt "High State". The High State is the
compound state derived from a group of template files stored on the
salt master or in the local cache.
'''
# a stack of active HighState objects during a state.highstate run
stack = []
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.opts = opts
self.client = salt.fileclient.get_file_client(self.opts)
BaseHighState.__init__(self, opts)
self.state = State(self.opts,
pillar_override,
jid,
pillar_enc,
proxy=proxy,
context=context,
mocked=mocked,
loader=loader,
initial_pillar=initial_pillar)
self.matchers = salt.loader.matchers(self.opts)
self.proxy = proxy
# tracks all pydsl state declarations globally across sls files
self._pydsl_all_decls = {}
# a stack of current rendering Sls objects, maintained and used by the pydsl renderer.
self._pydsl_render_stack = []
def push_active(self):
self.stack.append(self)
@classmethod
def clear_active(cls):
# Nuclear option
#
# Blow away the entire stack. Used primarily by the test runner but also
# useful in custom wrappers of the HighState class, to reset the stack
# to a fresh state.
cls.stack = []
@classmethod
def pop_active(cls):
cls.stack.pop()
@classmethod
def get_active(cls):
try:
return cls.stack[-1]
except IndexError:
return None
class MasterState(State):
'''
Create a State object for master side compiling
'''
def __init__(self, opts, minion):
State.__init__(self, opts)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
# Load a modified client interface that looks like the interface used
# from the minion, but uses remote execution
#
self.functions = salt.client.FunctionWrapper(
self.opts,
self.opts['id']
)
# Load the states, but they should not be used in this class apart
# from inspection
self.utils = salt.loader.utils(self.opts)
self.serializers = salt.loader.serializers(self.opts)
self.states = salt.loader.states(self.opts, self.functions, self.utils, self.serializers)
self.rend = salt.loader.render(self.opts, self.functions, states=self.states, context=self.state_con)
class MasterHighState(HighState):
'''
Execute highstate compilation from the master
'''
def __init__(self, master_opts, minion_opts, grains, id_,
saltenv=None):
# Force the fileclient to be local
opts = copy.deepcopy(minion_opts)
opts['file_client'] = 'local'
opts['file_roots'] = master_opts['master_roots']
opts['renderer'] = master_opts['renderer']
opts['state_top'] = master_opts['state_top']
opts['id'] = id_
opts['grains'] = grains
HighState.__init__(self, opts)
class RemoteHighState(object):
'''
Manage gathering the data from the master
'''
# XXX: This class doesn't seem to be used anywhere
def __init__(self, opts, grains):
self.opts = opts
self.grains = grains
self.serial = salt.payload.Serial(self.opts)
# self.auth = salt.crypt.SAuth(opts)
self.channel = salt.transport.client.ReqChannel.factory(self.opts['master_uri'])
self._closing = False
def compile_master(self):
'''
Return the state data from the master
'''
load = {'grains': self.grains,
'opts': self.opts,
'cmd': '_master_state'}
try:
return self.channel.send(load, tries=3, timeout=72000)
except SaltReqTimeoutError:
return {}
def destroy(self):
if self._closing:
return
self._closing = True
self.channel.close()
def __del__(self):
self.destroy()
|
saltstack/salt
|
salt/state.py
|
format_log
|
python
|
def format_log(ret):
'''
Format the state into a log message
'''
msg = ''
if isinstance(ret, dict):
# Looks like the ret may be a valid state return
if 'changes' in ret:
# Yep, looks like a valid state return
chg = ret['changes']
if not chg:
if ret['comment']:
msg = ret['comment']
else:
msg = 'No changes made for {0[name]}'.format(ret)
elif isinstance(chg, dict):
if 'diff' in chg:
if isinstance(chg['diff'], six.string_types):
msg = 'File changed:\n{0}'.format(chg['diff'])
if all([isinstance(x, dict) for x in six.itervalues(chg)]):
if all([('old' in x and 'new' in x)
for x in six.itervalues(chg)]):
msg = 'Made the following changes:\n'
for pkg in chg:
old = chg[pkg]['old']
if not old and old not in (False, None):
old = 'absent'
new = chg[pkg]['new']
if not new and new not in (False, None):
new = 'absent'
# This must be able to handle unicode as some package names contain
# non-ascii characters like "Français" or "Español". See Issue #33605.
msg += '\'{0}\' changed from \'{1}\' to \'{2}\'\n'.format(pkg, old, new)
if not msg:
msg = six.text_type(ret['changes'])
if ret['result'] is True or ret['result'] is None:
log.info(msg)
else:
log.error(msg)
else:
# catch unhandled data
log.info(six.text_type(ret))
|
Format the state into a log message
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L289-L330
|
[
"def itervalues(d, **kw):\n return d.itervalues(**kw)\n"
] |
# -*- coding: utf-8 -*-
'''
The State Compiler is used to execute states in Salt. A state is unlike
an execution module in that instead of just executing a command, it
ensures that a certain state is present on the system.
The data sent to the state calls is as follows:
{ 'state': '<state module name>',
'fun': '<state function name>',
'name': '<the name argument passed to all states>'
'argn': '<arbitrary argument, can have many of these>'
}
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import copy
import site
import fnmatch
import logging
import datetime
import traceback
import re
import time
import random
import collections
# Import salt libs
import salt.loader
import salt.minion
import salt.pillar
import salt.fileclient
import salt.utils.args
import salt.utils.crypt
import salt.utils.data
import salt.utils.decorators.state
import salt.utils.dictupdate
import salt.utils.event
import salt.utils.files
import salt.utils.hashutils
import salt.utils.immutabletypes as immutabletypes
import salt.utils.msgpack as msgpack
import salt.utils.platform
import salt.utils.process
import salt.utils.url
import salt.syspaths as syspaths
import salt.transport.client
from salt.serializers.msgpack import serialize as msgpack_serialize, deserialize as msgpack_deserialize
from salt.template import compile_template, compile_template_str
from salt.exceptions import (
SaltRenderError,
SaltReqTimeoutError
)
from salt.utils.odict import OrderedDict, DefaultOrderedDict
# Explicit late import to avoid circular import. DO NOT MOVE THIS.
import salt.utils.yamlloader as yamlloader
# Import third party libs
# pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext import six
from salt.ext.six.moves import map, range, reload_module
# pylint: enable=import-error,no-name-in-module,redefined-builtin
log = logging.getLogger(__name__)
# These are keywords passed to state module functions which are to be used
# by salt in this state module and not on the actual state module function
STATE_REQUISITE_KEYWORDS = frozenset([
'onchanges',
'onchanges_any',
'onfail',
'onfail_any',
'onfail_all',
'onfail_stop',
'prereq',
'prerequired',
'watch',
'watch_any',
'require',
'require_any',
'listen',
])
STATE_REQUISITE_IN_KEYWORDS = frozenset([
'onchanges_in',
'onfail_in',
'prereq_in',
'watch_in',
'require_in',
'listen_in',
])
STATE_RUNTIME_KEYWORDS = frozenset([
'fun',
'state',
'check_cmd',
'failhard',
'onlyif',
'unless',
'retry',
'order',
'parallel',
'prereq',
'prereq_in',
'prerequired',
'reload_modules',
'reload_grains',
'reload_pillar',
'runas',
'runas_password',
'fire_event',
'saltenv',
'use',
'use_in',
'__env__',
'__sls__',
'__id__',
'__orchestration_jid__',
'__pub_user',
'__pub_arg',
'__pub_id',
'__pub_jid',
'__pub_fun',
'__pub_fun_args',
'__pub_schedule',
'__pub_tgt',
'__pub_ret',
'__pub_pid',
'__pub_tgt_type',
'__prereq__',
])
STATE_INTERNAL_KEYWORDS = STATE_REQUISITE_KEYWORDS.union(STATE_REQUISITE_IN_KEYWORDS).union(STATE_RUNTIME_KEYWORDS)
def _odict_hashable(self):
return id(self)
OrderedDict.__hash__ = _odict_hashable
def split_low_tag(tag):
'''
Take a low tag and split it back into the low dict that it came from
'''
state, id_, name, fun = tag.split('_|-')
return {'state': state,
'__id__': id_,
'name': name,
'fun': fun}
def _gen_tag(low):
'''
Generate the running dict tag string from the low data structure
'''
return '{0[state]}_|-{0[__id__]}_|-{0[name]}_|-{0[fun]}'.format(low)
def _clean_tag(tag):
'''
Make tag name safe for filenames
'''
return salt.utils.files.safe_filename_leaf(tag)
def _l_tag(name, id_):
low = {'name': 'listen_{0}'.format(name),
'__id__': 'listen_{0}'.format(id_),
'state': 'Listen_Error',
'fun': 'Listen_Error'}
return _gen_tag(low)
def _calculate_fake_duration():
'''
Generate a NULL duration for when states do not run
but we want the results to be consistent.
'''
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - \
(datetime.datetime.utcnow() - datetime.datetime.now())
utc_finish_time = datetime.datetime.utcnow()
start_time = local_start_time.time().isoformat()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
return start_time, duration
def get_accumulator_dir(cachedir):
'''
Return the directory that accumulator data is stored in, creating it if it
doesn't exist.
'''
fn_ = os.path.join(cachedir, 'accumulator')
if not os.path.isdir(fn_):
# accumulator_dir is not present, create it
os.makedirs(fn_)
return fn_
def trim_req(req):
'''
Trim any function off of a requisite
'''
reqfirst = next(iter(req))
if '.' in reqfirst:
return {reqfirst.split('.')[0]: req[reqfirst]}
return req
def state_args(id_, state, high):
'''
Return a set of the arguments passed to the named state
'''
args = set()
if id_ not in high:
return args
if state not in high[id_]:
return args
for item in high[id_][state]:
if not isinstance(item, dict):
continue
if len(item) != 1:
continue
args.add(next(iter(item)))
return args
def find_name(name, state, high):
'''
Scan high data for the id referencing the given name and return a list of (IDs, state) tuples that match
Note: if `state` is sls, then we are looking for all IDs that match the given SLS
'''
ext_id = []
if name in high:
ext_id.append((name, state))
# if we are requiring an entire SLS, then we need to add ourselves to everything in that SLS
elif state == 'sls':
for nid, item in six.iteritems(high):
if item['__sls__'] == name:
ext_id.append((nid, next(iter(item))))
# otherwise we are requiring a single state, lets find it
else:
# We need to scan for the name
for nid in high:
if state in high[nid]:
if isinstance(high[nid][state], list):
for arg in high[nid][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if arg[next(iter(arg))] == name:
ext_id.append((nid, state))
return ext_id
def find_sls_ids(sls, high):
'''
Scan for all ids in the given sls and return them in a dict; {name: state}
'''
ret = []
for nid, item in six.iteritems(high):
try:
sls_tgt = item['__sls__']
except TypeError:
if nid != '__exclude__':
log.error(
'Invalid non-dict item \'%s\' in high data. Value: %r',
nid, item
)
continue
else:
if sls_tgt == sls:
for st_ in item:
if st_.startswith('__'):
continue
ret.append((nid, st_))
return ret
def master_compile(master_opts, minion_opts, grains, id_, saltenv):
'''
Compile the master side low state data, and build the hidden state file
'''
st_ = MasterHighState(master_opts, minion_opts, grains, id_, saltenv)
return st_.compile_highstate()
def ishashable(obj):
try:
hash(obj)
except TypeError:
return False
return True
def mock_ret(cdata):
'''
Returns a mocked return dict with information about the run, without
executing the state function
'''
# As this is expanded it should be sent into the execution module
# layer or it should be turned into a standalone loader system
if cdata['args']:
name = cdata['args'][0]
else:
name = cdata['kwargs']['name']
return {'name': name,
'comment': 'Not called, mocked',
'changes': {},
'result': True}
class StateError(Exception):
'''
Custom exception class.
'''
pass
class Compiler(object):
'''
Class used to compile and manage the High Data structure
'''
def __init__(self, opts, renderers):
self.opts = opts
self.rend = renderers
def render_template(self, template, **kwargs):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'],
**kwargs)
if not high:
return high
return self.pad_funcs(high)
def pad_funcs(self, high):
'''
Turns dot delimited function refs into function strings
'''
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state? It needs to be padded!
if '.' in high[name]:
comps = high[name].split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}'.format(
name,
body['__sls__'],
type(name).__name__
)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(('The {0}'
' statement in state \'{1}\' in SLS \'{2}\' '
'needs to be formed as a list').format(
argfirst,
name,
body['__sls__']
))
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = {'state': state}
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append((
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
))
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'is SLS {1}\n'
).format(
six.text_type(req_val),
body['__sls__']))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(('Multiple dictionaries '
'defined in argument of state \'{0}\' in SLS'
' \'{1}\'').format(
name,
body['__sls__']))
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(('No function declared in state \'{0}\' in'
' SLS \'{1}\'').format(state, body['__sls__']))
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunk['name'] = salt.utils.data.decode(chunk['name'])
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = {'state': state,
'name': name}
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
continue
else:
chunk.update(arg)
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order = name_order + 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associtaed ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if body.get('__sls__', '') in ex_sls:
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
class HighState(BaseHighState):
'''
Generate and execute the salt "High State". The High State is the
compound state derived from a group of template files stored on the
salt master or in the local cache.
'''
# a stack of active HighState objects during a state.highstate run
stack = []
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.opts = opts
self.client = salt.fileclient.get_file_client(self.opts)
BaseHighState.__init__(self, opts)
self.state = State(self.opts,
pillar_override,
jid,
pillar_enc,
proxy=proxy,
context=context,
mocked=mocked,
loader=loader,
initial_pillar=initial_pillar)
self.matchers = salt.loader.matchers(self.opts)
self.proxy = proxy
# tracks all pydsl state declarations globally across sls files
self._pydsl_all_decls = {}
# a stack of current rendering Sls objects, maintained and used by the pydsl renderer.
self._pydsl_render_stack = []
def push_active(self):
self.stack.append(self)
@classmethod
def clear_active(cls):
# Nuclear option
#
# Blow away the entire stack. Used primarily by the test runner but also
# useful in custom wrappers of the HighState class, to reset the stack
# to a fresh state.
cls.stack = []
@classmethod
def pop_active(cls):
cls.stack.pop()
@classmethod
def get_active(cls):
try:
return cls.stack[-1]
except IndexError:
return None
class MasterState(State):
'''
Create a State object for master side compiling
'''
def __init__(self, opts, minion):
State.__init__(self, opts)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
# Load a modified client interface that looks like the interface used
# from the minion, but uses remote execution
#
self.functions = salt.client.FunctionWrapper(
self.opts,
self.opts['id']
)
# Load the states, but they should not be used in this class apart
# from inspection
self.utils = salt.loader.utils(self.opts)
self.serializers = salt.loader.serializers(self.opts)
self.states = salt.loader.states(self.opts, self.functions, self.utils, self.serializers)
self.rend = salt.loader.render(self.opts, self.functions, states=self.states, context=self.state_con)
class MasterHighState(HighState):
'''
Execute highstate compilation from the master
'''
def __init__(self, master_opts, minion_opts, grains, id_,
saltenv=None):
# Force the fileclient to be local
opts = copy.deepcopy(minion_opts)
opts['file_client'] = 'local'
opts['file_roots'] = master_opts['master_roots']
opts['renderer'] = master_opts['renderer']
opts['state_top'] = master_opts['state_top']
opts['id'] = id_
opts['grains'] = grains
HighState.__init__(self, opts)
class RemoteHighState(object):
'''
Manage gathering the data from the master
'''
# XXX: This class doesn't seem to be used anywhere
def __init__(self, opts, grains):
self.opts = opts
self.grains = grains
self.serial = salt.payload.Serial(self.opts)
# self.auth = salt.crypt.SAuth(opts)
self.channel = salt.transport.client.ReqChannel.factory(self.opts['master_uri'])
self._closing = False
def compile_master(self):
'''
Return the state data from the master
'''
load = {'grains': self.grains,
'opts': self.opts,
'cmd': '_master_state'}
try:
return self.channel.send(load, tries=3, timeout=72000)
except SaltReqTimeoutError:
return {}
def destroy(self):
if self._closing:
return
self._closing = True
self.channel.close()
def __del__(self):
self.destroy()
|
saltstack/salt
|
salt/state.py
|
master_compile
|
python
|
def master_compile(master_opts, minion_opts, grains, id_, saltenv):
'''
Compile the master side low state data, and build the hidden state file
'''
st_ = MasterHighState(master_opts, minion_opts, grains, id_, saltenv)
return st_.compile_highstate()
|
Compile the master side low state data, and build the hidden state file
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L333-L338
|
[
"def compile_highstate(self):\n '''\n Return just the highstate or the errors\n '''\n err = []\n top = self.get_top()\n err += self.verify_tops(top)\n matches = self.top_matches(top)\n high, errors = self.render_highstate(matches)\n err += errors\n\n if err:\n return err\n\n return high\n"
] |
# -*- coding: utf-8 -*-
'''
The State Compiler is used to execute states in Salt. A state is unlike
an execution module in that instead of just executing a command, it
ensures that a certain state is present on the system.
The data sent to the state calls is as follows:
{ 'state': '<state module name>',
'fun': '<state function name>',
'name': '<the name argument passed to all states>'
'argn': '<arbitrary argument, can have many of these>'
}
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import sys
import copy
import site
import fnmatch
import logging
import datetime
import traceback
import re
import time
import random
import collections
# Import salt libs
import salt.loader
import salt.minion
import salt.pillar
import salt.fileclient
import salt.utils.args
import salt.utils.crypt
import salt.utils.data
import salt.utils.decorators.state
import salt.utils.dictupdate
import salt.utils.event
import salt.utils.files
import salt.utils.hashutils
import salt.utils.immutabletypes as immutabletypes
import salt.utils.msgpack as msgpack
import salt.utils.platform
import salt.utils.process
import salt.utils.url
import salt.syspaths as syspaths
import salt.transport.client
from salt.serializers.msgpack import serialize as msgpack_serialize, deserialize as msgpack_deserialize
from salt.template import compile_template, compile_template_str
from salt.exceptions import (
SaltRenderError,
SaltReqTimeoutError
)
from salt.utils.odict import OrderedDict, DefaultOrderedDict
# Explicit late import to avoid circular import. DO NOT MOVE THIS.
import salt.utils.yamlloader as yamlloader
# Import third party libs
# pylint: disable=import-error,no-name-in-module,redefined-builtin
from salt.ext import six
from salt.ext.six.moves import map, range, reload_module
# pylint: enable=import-error,no-name-in-module,redefined-builtin
log = logging.getLogger(__name__)
# These are keywords passed to state module functions which are to be used
# by salt in this state module and not on the actual state module function
STATE_REQUISITE_KEYWORDS = frozenset([
'onchanges',
'onchanges_any',
'onfail',
'onfail_any',
'onfail_all',
'onfail_stop',
'prereq',
'prerequired',
'watch',
'watch_any',
'require',
'require_any',
'listen',
])
STATE_REQUISITE_IN_KEYWORDS = frozenset([
'onchanges_in',
'onfail_in',
'prereq_in',
'watch_in',
'require_in',
'listen_in',
])
STATE_RUNTIME_KEYWORDS = frozenset([
'fun',
'state',
'check_cmd',
'failhard',
'onlyif',
'unless',
'retry',
'order',
'parallel',
'prereq',
'prereq_in',
'prerequired',
'reload_modules',
'reload_grains',
'reload_pillar',
'runas',
'runas_password',
'fire_event',
'saltenv',
'use',
'use_in',
'__env__',
'__sls__',
'__id__',
'__orchestration_jid__',
'__pub_user',
'__pub_arg',
'__pub_id',
'__pub_jid',
'__pub_fun',
'__pub_fun_args',
'__pub_schedule',
'__pub_tgt',
'__pub_ret',
'__pub_pid',
'__pub_tgt_type',
'__prereq__',
])
STATE_INTERNAL_KEYWORDS = STATE_REQUISITE_KEYWORDS.union(STATE_REQUISITE_IN_KEYWORDS).union(STATE_RUNTIME_KEYWORDS)
def _odict_hashable(self):
return id(self)
OrderedDict.__hash__ = _odict_hashable
def split_low_tag(tag):
'''
Take a low tag and split it back into the low dict that it came from
'''
state, id_, name, fun = tag.split('_|-')
return {'state': state,
'__id__': id_,
'name': name,
'fun': fun}
def _gen_tag(low):
'''
Generate the running dict tag string from the low data structure
'''
return '{0[state]}_|-{0[__id__]}_|-{0[name]}_|-{0[fun]}'.format(low)
def _clean_tag(tag):
'''
Make tag name safe for filenames
'''
return salt.utils.files.safe_filename_leaf(tag)
def _l_tag(name, id_):
low = {'name': 'listen_{0}'.format(name),
'__id__': 'listen_{0}'.format(id_),
'state': 'Listen_Error',
'fun': 'Listen_Error'}
return _gen_tag(low)
def _calculate_fake_duration():
'''
Generate a NULL duration for when states do not run
but we want the results to be consistent.
'''
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - \
(datetime.datetime.utcnow() - datetime.datetime.now())
utc_finish_time = datetime.datetime.utcnow()
start_time = local_start_time.time().isoformat()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
return start_time, duration
def get_accumulator_dir(cachedir):
'''
Return the directory that accumulator data is stored in, creating it if it
doesn't exist.
'''
fn_ = os.path.join(cachedir, 'accumulator')
if not os.path.isdir(fn_):
# accumulator_dir is not present, create it
os.makedirs(fn_)
return fn_
def trim_req(req):
'''
Trim any function off of a requisite
'''
reqfirst = next(iter(req))
if '.' in reqfirst:
return {reqfirst.split('.')[0]: req[reqfirst]}
return req
def state_args(id_, state, high):
'''
Return a set of the arguments passed to the named state
'''
args = set()
if id_ not in high:
return args
if state not in high[id_]:
return args
for item in high[id_][state]:
if not isinstance(item, dict):
continue
if len(item) != 1:
continue
args.add(next(iter(item)))
return args
def find_name(name, state, high):
'''
Scan high data for the id referencing the given name and return a list of (IDs, state) tuples that match
Note: if `state` is sls, then we are looking for all IDs that match the given SLS
'''
ext_id = []
if name in high:
ext_id.append((name, state))
# if we are requiring an entire SLS, then we need to add ourselves to everything in that SLS
elif state == 'sls':
for nid, item in six.iteritems(high):
if item['__sls__'] == name:
ext_id.append((nid, next(iter(item))))
# otherwise we are requiring a single state, lets find it
else:
# We need to scan for the name
for nid in high:
if state in high[nid]:
if isinstance(high[nid][state], list):
for arg in high[nid][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if arg[next(iter(arg))] == name:
ext_id.append((nid, state))
return ext_id
def find_sls_ids(sls, high):
'''
Scan for all ids in the given sls and return them in a dict; {name: state}
'''
ret = []
for nid, item in six.iteritems(high):
try:
sls_tgt = item['__sls__']
except TypeError:
if nid != '__exclude__':
log.error(
'Invalid non-dict item \'%s\' in high data. Value: %r',
nid, item
)
continue
else:
if sls_tgt == sls:
for st_ in item:
if st_.startswith('__'):
continue
ret.append((nid, st_))
return ret
def format_log(ret):
'''
Format the state into a log message
'''
msg = ''
if isinstance(ret, dict):
# Looks like the ret may be a valid state return
if 'changes' in ret:
# Yep, looks like a valid state return
chg = ret['changes']
if not chg:
if ret['comment']:
msg = ret['comment']
else:
msg = 'No changes made for {0[name]}'.format(ret)
elif isinstance(chg, dict):
if 'diff' in chg:
if isinstance(chg['diff'], six.string_types):
msg = 'File changed:\n{0}'.format(chg['diff'])
if all([isinstance(x, dict) for x in six.itervalues(chg)]):
if all([('old' in x and 'new' in x)
for x in six.itervalues(chg)]):
msg = 'Made the following changes:\n'
for pkg in chg:
old = chg[pkg]['old']
if not old and old not in (False, None):
old = 'absent'
new = chg[pkg]['new']
if not new and new not in (False, None):
new = 'absent'
# This must be able to handle unicode as some package names contain
# non-ascii characters like "Français" or "Español". See Issue #33605.
msg += '\'{0}\' changed from \'{1}\' to \'{2}\'\n'.format(pkg, old, new)
if not msg:
msg = six.text_type(ret['changes'])
if ret['result'] is True or ret['result'] is None:
log.info(msg)
else:
log.error(msg)
else:
# catch unhandled data
log.info(six.text_type(ret))
def ishashable(obj):
try:
hash(obj)
except TypeError:
return False
return True
def mock_ret(cdata):
'''
Returns a mocked return dict with information about the run, without
executing the state function
'''
# As this is expanded it should be sent into the execution module
# layer or it should be turned into a standalone loader system
if cdata['args']:
name = cdata['args'][0]
else:
name = cdata['kwargs']['name']
return {'name': name,
'comment': 'Not called, mocked',
'changes': {},
'result': True}
class StateError(Exception):
'''
Custom exception class.
'''
pass
class Compiler(object):
'''
Class used to compile and manage the High Data structure
'''
def __init__(self, opts, renderers):
self.opts = opts
self.rend = renderers
def render_template(self, template, **kwargs):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'],
**kwargs)
if not high:
return high
return self.pad_funcs(high)
def pad_funcs(self, high):
'''
Turns dot delimited function refs into function strings
'''
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state? It needs to be padded!
if '.' in high[name]:
comps = high[name].split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}'.format(
name,
body['__sls__'],
type(name).__name__
)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(('The {0}'
' statement in state \'{1}\' in SLS \'{2}\' '
'needs to be formed as a list').format(
argfirst,
name,
body['__sls__']
))
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = {'state': state}
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append((
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
))
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'is SLS {1}\n'
).format(
six.text_type(req_val),
body['__sls__']))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(('Multiple dictionaries '
'defined in argument of state \'{0}\' in SLS'
' \'{1}\'').format(
name,
body['__sls__']))
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(('No function declared in state \'{0}\' in'
' SLS \'{1}\'').format(state, body['__sls__']))
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunk['name'] = salt.utils.data.decode(chunk['name'])
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = {'state': state,
'name': name}
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
continue
else:
chunk.update(arg)
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order = name_order + 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associtaed ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if body.get('__sls__', '') in ex_sls:
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
class HighState(BaseHighState):
'''
Generate and execute the salt "High State". The High State is the
compound state derived from a group of template files stored on the
salt master or in the local cache.
'''
# a stack of active HighState objects during a state.highstate run
stack = []
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.opts = opts
self.client = salt.fileclient.get_file_client(self.opts)
BaseHighState.__init__(self, opts)
self.state = State(self.opts,
pillar_override,
jid,
pillar_enc,
proxy=proxy,
context=context,
mocked=mocked,
loader=loader,
initial_pillar=initial_pillar)
self.matchers = salt.loader.matchers(self.opts)
self.proxy = proxy
# tracks all pydsl state declarations globally across sls files
self._pydsl_all_decls = {}
# a stack of current rendering Sls objects, maintained and used by the pydsl renderer.
self._pydsl_render_stack = []
def push_active(self):
self.stack.append(self)
@classmethod
def clear_active(cls):
# Nuclear option
#
# Blow away the entire stack. Used primarily by the test runner but also
# useful in custom wrappers of the HighState class, to reset the stack
# to a fresh state.
cls.stack = []
@classmethod
def pop_active(cls):
cls.stack.pop()
@classmethod
def get_active(cls):
try:
return cls.stack[-1]
except IndexError:
return None
class MasterState(State):
'''
Create a State object for master side compiling
'''
def __init__(self, opts, minion):
State.__init__(self, opts)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
# Load a modified client interface that looks like the interface used
# from the minion, but uses remote execution
#
self.functions = salt.client.FunctionWrapper(
self.opts,
self.opts['id']
)
# Load the states, but they should not be used in this class apart
# from inspection
self.utils = salt.loader.utils(self.opts)
self.serializers = salt.loader.serializers(self.opts)
self.states = salt.loader.states(self.opts, self.functions, self.utils, self.serializers)
self.rend = salt.loader.render(self.opts, self.functions, states=self.states, context=self.state_con)
class MasterHighState(HighState):
'''
Execute highstate compilation from the master
'''
def __init__(self, master_opts, minion_opts, grains, id_,
saltenv=None):
# Force the fileclient to be local
opts = copy.deepcopy(minion_opts)
opts['file_client'] = 'local'
opts['file_roots'] = master_opts['master_roots']
opts['renderer'] = master_opts['renderer']
opts['state_top'] = master_opts['state_top']
opts['id'] = id_
opts['grains'] = grains
HighState.__init__(self, opts)
class RemoteHighState(object):
'''
Manage gathering the data from the master
'''
# XXX: This class doesn't seem to be used anywhere
def __init__(self, opts, grains):
self.opts = opts
self.grains = grains
self.serial = salt.payload.Serial(self.opts)
# self.auth = salt.crypt.SAuth(opts)
self.channel = salt.transport.client.ReqChannel.factory(self.opts['master_uri'])
self._closing = False
def compile_master(self):
'''
Return the state data from the master
'''
load = {'grains': self.grains,
'opts': self.opts,
'cmd': '_master_state'}
try:
return self.channel.send(load, tries=3, timeout=72000)
except SaltReqTimeoutError:
return {}
def destroy(self):
if self._closing:
return
self._closing = True
self.channel.close()
def __del__(self):
self.destroy()
|
saltstack/salt
|
salt/state.py
|
Compiler.render_template
|
python
|
def render_template(self, template, **kwargs):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'],
**kwargs)
if not high:
return high
return self.pad_funcs(high)
|
Enforce the states in a template
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L381-L393
|
[
"def compile_template(template,\n renderers,\n default,\n blacklist,\n whitelist,\n saltenv='base',\n sls='',\n input_data='',\n **kwargs):\n '''\n Take the path to a template and return the high data structure\n derived from the template.\n\n Helpers:\n\n :param mask_value:\n Mask value for debugging purposes (prevent sensitive information etc)\n example: \"mask_value=\"pass*\". All \"passwd\", \"password\", \"pass\" will\n be masked (as text).\n '''\n\n # if any error occurs, we return an empty dictionary\n ret = {}\n\n log.debug('compile template: %s', template)\n\n if 'env' in kwargs:\n # \"env\" is not supported; Use \"saltenv\".\n kwargs.pop('env')\n\n if template != ':string:':\n # Template was specified incorrectly\n if not isinstance(template, six.string_types):\n log.error('Template was specified incorrectly: %s', template)\n return ret\n # Template does not exist\n if not os.path.isfile(template):\n log.error('Template does not exist: %s', template)\n return ret\n # Template is an empty file\n if salt.utils.files.is_empty(template):\n log.debug('Template is an empty file: %s', template)\n return ret\n\n with codecs.open(template, encoding=SLS_ENCODING) as ifile:\n # data input to the first render function in the pipe\n input_data = ifile.read()\n if not input_data.strip():\n # Template is nothing but whitespace\n log.error('Template is nothing but whitespace: %s', template)\n return ret\n\n # Get the list of render funcs in the render pipe line.\n render_pipe = template_shebang(template, renderers, default, blacklist, whitelist, input_data)\n\n windows_newline = '\\r\\n' in input_data\n\n input_data = StringIO(input_data)\n for render, argline in render_pipe:\n if salt.utils.stringio.is_readable(input_data):\n input_data.seek(0) # pylint: disable=no-member\n render_kwargs = dict(renderers=renderers, tmplpath=template)\n render_kwargs.update(kwargs)\n if argline:\n render_kwargs['argline'] = argline\n start = time.time()\n ret = render(input_data, saltenv, sls, **render_kwargs)\n log.profile(\n 'Time (in seconds) to render \\'%s\\' using \\'%s\\' renderer: %s',\n template,\n render.__module__.split('.')[-1],\n time.time() - start\n )\n if ret is None:\n # The file is empty or is being written elsewhere\n time.sleep(0.01)\n ret = render(input_data, saltenv, sls, **render_kwargs)\n input_data = ret\n if log.isEnabledFor(logging.GARBAGE): # pylint: disable=no-member\n # If ret is not a StringIO (which means it was rendered using\n # yaml, mako, or another engine which renders to a data\n # structure) we don't want to log this.\n if salt.utils.stringio.is_readable(ret):\n log.debug('Rendered data from file: %s:\\n%s', template,\n salt.utils.sanitizers.mask_args_value(salt.utils.data.decode(ret.read()),\n kwargs.get('mask_value'))) # pylint: disable=no-member\n ret.seek(0) # pylint: disable=no-member\n\n # Preserve newlines from original template\n if windows_newline:\n if salt.utils.stringio.is_readable(ret):\n is_stringio = True\n contents = ret.read()\n else:\n is_stringio = False\n contents = ret\n\n if isinstance(contents, six.string_types):\n if '\\r\\n' not in contents:\n contents = contents.replace('\\n', '\\r\\n')\n ret = StringIO(contents) if is_stringio else contents\n else:\n if is_stringio:\n ret.seek(0)\n return ret\n",
"def pad_funcs(self, high):\n '''\n Turns dot delimited function refs into function strings\n '''\n for name in high:\n if not isinstance(high[name], dict):\n if isinstance(high[name], six.string_types):\n # Is this is a short state? It needs to be padded!\n if '.' in high[name]:\n comps = high[name].split('.')\n if len(comps) >= 2:\n # Merge the comps\n comps[1] = '.'.join(comps[1:len(comps)])\n high[name] = {\n # '__sls__': template,\n # '__env__': None,\n comps[0]: [comps[1]]\n }\n continue\n continue\n skeys = set()\n for key in sorted(high[name]):\n if key.startswith('_'):\n continue\n if not isinstance(high[name][key], list):\n continue\n if '.' in key:\n comps = key.split('.')\n if len(comps) >= 2:\n # Merge the comps\n comps[1] = '.'.join(comps[1:len(comps)])\n # Salt doesn't support state files such as:\n #\n # /etc/redis/redis.conf:\n # file.managed:\n # - user: redis\n # - group: redis\n # - mode: 644\n # file.comment:\n # - regex: ^requirepass\n if comps[0] in skeys:\n continue\n high[name][comps[0]] = high[name].pop(key)\n high[name][comps[0]].append(comps[1])\n skeys.add(comps[0])\n continue\n skeys.add(key)\n return high\n"
] |
class Compiler(object):
'''
Class used to compile and manage the High Data structure
'''
def __init__(self, opts, renderers):
self.opts = opts
self.rend = renderers
def pad_funcs(self, high):
'''
Turns dot delimited function refs into function strings
'''
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state? It needs to be padded!
if '.' in high[name]:
comps = high[name].split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}'.format(
name,
body['__sls__'],
type(name).__name__
)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(('The {0}'
' statement in state \'{1}\' in SLS \'{2}\' '
'needs to be formed as a list').format(
argfirst,
name,
body['__sls__']
))
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = {'state': state}
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append((
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
))
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'is SLS {1}\n'
).format(
six.text_type(req_val),
body['__sls__']))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(('Multiple dictionaries '
'defined in argument of state \'{0}\' in SLS'
' \'{1}\'').format(
name,
body['__sls__']))
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(('No function declared in state \'{0}\' in'
' SLS \'{1}\'').format(state, body['__sls__']))
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunk['name'] = salt.utils.data.decode(chunk['name'])
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = {'state': state,
'name': name}
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
continue
else:
chunk.update(arg)
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order = name_order + 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associtaed ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if body.get('__sls__', '') in ex_sls:
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
|
saltstack/salt
|
salt/state.py
|
Compiler.pad_funcs
|
python
|
def pad_funcs(self, high):
'''
Turns dot delimited function refs into function strings
'''
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state? It needs to be padded!
if '.' in high[name]:
comps = high[name].split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high
|
Turns dot delimited function refs into function strings
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L395-L442
| null |
class Compiler(object):
'''
Class used to compile and manage the High Data structure
'''
def __init__(self, opts, renderers):
self.opts = opts
self.rend = renderers
def render_template(self, template, **kwargs):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'],
**kwargs)
if not high:
return high
return self.pad_funcs(high)
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}'.format(
name,
body['__sls__'],
type(name).__name__
)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(('The {0}'
' statement in state \'{1}\' in SLS \'{2}\' '
'needs to be formed as a list').format(
argfirst,
name,
body['__sls__']
))
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = {'state': state}
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append((
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
))
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'is SLS {1}\n'
).format(
six.text_type(req_val),
body['__sls__']))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(('Multiple dictionaries '
'defined in argument of state \'{0}\' in SLS'
' \'{1}\'').format(
name,
body['__sls__']))
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(('No function declared in state \'{0}\' in'
' SLS \'{1}\'').format(state, body['__sls__']))
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunk['name'] = salt.utils.data.decode(chunk['name'])
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = {'state': state,
'name': name}
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
continue
else:
chunk.update(arg)
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order = name_order + 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associtaed ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if body.get('__sls__', '') in ex_sls:
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
|
saltstack/salt
|
salt/state.py
|
Compiler.verify_high
|
python
|
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}'.format(
name,
body['__sls__'],
type(name).__name__
)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(('The {0}'
' statement in state \'{1}\' in SLS \'{2}\' '
'needs to be formed as a list').format(
argfirst,
name,
body['__sls__']
))
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = {'state': state}
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append((
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
))
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'is SLS {1}\n'
).format(
six.text_type(req_val),
body['__sls__']))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(('Multiple dictionaries '
'defined in argument of state \'{0}\' in SLS'
' \'{1}\'').format(
name,
body['__sls__']))
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(('No function declared in state \'{0}\' in'
' SLS \'{1}\'').format(state, body['__sls__']))
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
|
Verify that the high data is viable and follows the data structure
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L444-L584
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n"
] |
class Compiler(object):
'''
Class used to compile and manage the High Data structure
'''
def __init__(self, opts, renderers):
self.opts = opts
self.rend = renderers
def render_template(self, template, **kwargs):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'],
**kwargs)
if not high:
return high
return self.pad_funcs(high)
def pad_funcs(self, high):
'''
Turns dot delimited function refs into function strings
'''
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state? It needs to be padded!
if '.' in high[name]:
comps = high[name].split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunk['name'] = salt.utils.data.decode(chunk['name'])
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = {'state': state,
'name': name}
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
continue
else:
chunk.update(arg)
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order = name_order + 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associtaed ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if body.get('__sls__', '') in ex_sls:
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
|
saltstack/salt
|
salt/state.py
|
Compiler.order_chunks
|
python
|
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunk['name'] = salt.utils.data.decode(chunk['name'])
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
|
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L586-L618
|
[
"def decode(data, encoding=None, errors='strict', keep=False,\n normalize=False, preserve_dict_class=False, preserve_tuples=False,\n to_str=False):\n '''\n Generic function which will decode whichever type is passed, if necessary.\n Optionally use to_str=True to ensure strings are str types and not unicode\n on Python 2.\n\n If `strict` is True, and `keep` is False, and we fail to decode, a\n UnicodeDecodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where decoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs, such as in the case of cp.recv.\n\n If `normalize` is True, then unicodedata.normalize() will be used to\n normalize unicode strings down to a single code point per glyph. It is\n recommended not to normalize unless you know what you're doing. For\n instance, if `data` contains a dictionary, it is possible that normalizing\n will lead to data loss because the following two strings will normalize to\n the same value:\n\n - u'\\\\u044f\\\\u0438\\\\u0306\\\\u0446\\\\u0430.txt'\n - u'\\\\u044f\\\\u0439\\\\u0446\\\\u0430.txt'\n\n One good use case for normalization is in the test suite. For example, on\n some platforms such as Mac OS, os.listdir() will produce the first of the\n two strings above, in which \"й\" is represented as two code points (i.e. one\n for the base character, and one for the breve mark). Normalizing allows for\n a more reliable test case.\n '''\n _decode_func = salt.utils.stringutils.to_unicode \\\n if not to_str \\\n else salt.utils.stringutils.to_str\n if isinstance(data, Mapping):\n return decode_dict(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, list):\n return decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, tuple):\n return decode_tuple(data, encoding, errors, keep, normalize,\n preserve_dict_class, to_str) \\\n if preserve_tuples \\\n else decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n else:\n try:\n data = _decode_func(data, encoding, errors, normalize)\n except TypeError:\n # to_unicode raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply means we\n # are going to leave the value as-is.\n pass\n except UnicodeDecodeError:\n if not keep:\n raise\n return data\n"
] |
class Compiler(object):
'''
Class used to compile and manage the High Data structure
'''
def __init__(self, opts, renderers):
self.opts = opts
self.rend = renderers
def render_template(self, template, **kwargs):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'],
**kwargs)
if not high:
return high
return self.pad_funcs(high)
def pad_funcs(self, high):
'''
Turns dot delimited function refs into function strings
'''
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state? It needs to be padded!
if '.' in high[name]:
comps = high[name].split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}'.format(
name,
body['__sls__'],
type(name).__name__
)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(('The {0}'
' statement in state \'{1}\' in SLS \'{2}\' '
'needs to be formed as a list').format(
argfirst,
name,
body['__sls__']
))
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = {'state': state}
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append((
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
))
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'is SLS {1}\n'
).format(
six.text_type(req_val),
body['__sls__']))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(('Multiple dictionaries '
'defined in argument of state \'{0}\' in SLS'
' \'{1}\'').format(
name,
body['__sls__']))
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(('No function declared in state \'{0}\' in'
' SLS \'{1}\'').format(state, body['__sls__']))
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def compile_high_data(self, high):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = {'state': state,
'name': name}
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
continue
else:
chunk.update(arg)
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order = name_order + 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associtaed ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if body.get('__sls__', '') in ex_sls:
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
|
saltstack/salt
|
salt/state.py
|
Compiler.apply_exclude
|
python
|
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associtaed ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if body.get('__sls__', '') in ex_sls:
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
|
Read in the __exclude__ list and remove all excluded objects from the
high data
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L677-L711
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n"
] |
class Compiler(object):
'''
Class used to compile and manage the High Data structure
'''
def __init__(self, opts, renderers):
self.opts = opts
self.rend = renderers
def render_template(self, template, **kwargs):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'],
**kwargs)
if not high:
return high
return self.pad_funcs(high)
def pad_funcs(self, high):
'''
Turns dot delimited function refs into function strings
'''
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state? It needs to be padded!
if '.' in high[name]:
comps = high[name].split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
if len(comps) >= 2:
# Merge the comps
comps[1] = '.'.join(comps[1:len(comps)])
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}'.format(
name,
body['__sls__'],
type(name).__name__
)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(('The {0}'
' statement in state \'{1}\' in SLS \'{2}\' '
'needs to be formed as a list').format(
argfirst,
name,
body['__sls__']
))
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = {'state': state}
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append((
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
))
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'is SLS {1}\n'
).format(
six.text_type(req_val),
body['__sls__']))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(('Multiple dictionaries '
'defined in argument of state \'{0}\' in SLS'
' \'{1}\'').format(
name,
body['__sls__']))
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(('No function declared in state \'{0}\' in'
' SLS \'{1}\'').format(state, body['__sls__']))
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunk['name'] = salt.utils.data.decode(chunk['name'])
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = {'state': state,
'name': name}
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
continue
else:
chunk.update(arg)
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order = name_order + 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
|
saltstack/salt
|
salt/state.py
|
State._gather_pillar
|
python
|
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
|
Whenever a state run starts, gather the pillar data fresh
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L767-L808
|
[
"def load(stream, Loader=SaltYamlSafeLoader):\n return yaml.load(stream, Loader=Loader)\n",
"def get_pillar(opts, grains, minion_id, saltenv=None, ext=None, funcs=None,\n pillar_override=None, pillarenv=None, extra_minion_data=None):\n '''\n Return the correct pillar driver based on the file_client option\n '''\n file_client = opts['file_client']\n if opts.get('master_type') == 'disable' and file_client == 'remote':\n file_client = 'local'\n ptype = {\n 'remote': RemotePillar,\n 'local': Pillar\n }.get(file_client, Pillar)\n # If local pillar and we're caching, run through the cache system first\n log.debug('Determining pillar cache')\n if opts['pillar_cache']:\n log.info('Compiling pillar from cache')\n log.debug('get_pillar using pillar cache with ext: %s', ext)\n return PillarCache(opts, grains, minion_id, saltenv, ext=ext, functions=funcs,\n pillar_override=pillar_override, pillarenv=pillarenv)\n return ptype(opts, grains, minion_id, saltenv, ext, functions=funcs,\n pillar_override=pillar_override, pillarenv=pillarenv,\n extra_minion_data=extra_minion_data)\n",
"def decrypt(data,\n rend,\n translate_newlines=False,\n renderers=None,\n opts=None,\n valid_rend=None):\n '''\n .. versionadded:: 2017.7.0\n\n Decrypt a data structure using the specified renderer. Written originally\n as a common codebase to handle decryption of encrypted elements within\n Pillar data, but should be flexible enough for other uses as well.\n\n Returns the decrypted result, but any decryption renderer should be\n recursively decrypting mutable types in-place, so any data structure passed\n should be automagically decrypted using this function. Immutable types\n obviously won't, so it's a good idea to check if ``data`` is hashable in\n the calling function, and replace the original value with the decrypted\n result if that is not the case. For an example of this, see\n salt.pillar.Pillar.decrypt_pillar().\n\n data\n The data to be decrypted. This can be a string of ciphertext or a data\n structure. If it is a data structure, the items in the data structure\n will be recursively decrypted.\n\n rend\n The renderer used to decrypt\n\n translate_newlines : False\n If True, then the renderer will convert a literal backslash followed by\n an 'n' into a newline before performing the decryption.\n\n renderers\n Optionally pass a loader instance containing loaded renderer functions.\n If not passed, then the ``opts`` will be required and will be used to\n invoke the loader to get the available renderers. Where possible,\n renderers should be passed to avoid the overhead of loading them here.\n\n opts\n The master/minion configuration opts. Used only if renderers are not\n passed.\n\n valid_rend\n A list containing valid renderers, used to restrict the renderers which\n this function will be allowed to use. If not passed, no restriction\n will be made.\n '''\n try:\n if valid_rend and rend not in valid_rend:\n raise SaltInvocationError(\n '\\'{0}\\' is not a valid decryption renderer. Valid choices '\n 'are: {1}'.format(rend, ', '.join(valid_rend))\n )\n except TypeError as exc:\n # SaltInvocationError inherits TypeError, so check for it first and\n # raise if needed.\n if isinstance(exc, SaltInvocationError):\n raise\n # 'valid' argument is not iterable\n log.error('Non-iterable value %s passed for valid_rend', valid_rend)\n\n if renderers is None:\n if opts is None:\n raise TypeError('opts are required')\n renderers = salt.loader.render(opts, {})\n\n rend_func = renderers.get(rend)\n if rend_func is None:\n raise SaltInvocationError(\n 'Decryption renderer \\'{0}\\' is not available'.format(rend)\n )\n\n return rend_func(data, translate_newlines=translate_newlines)\n"
] |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State._mod_init
|
python
|
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
|
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L810-L827
| null |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State._mod_aggregate
|
python
|
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
|
Execute the aggregation systems to runtime modify the low chunk
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L829-L848
| null |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State._run_check
|
python
|
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
|
Check that unless doesn't return 0, and that onlyif returns a 0.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L850-L876
| null |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State._run_check_onlyif
|
python
|
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
|
Check that unless doesn't return 0, and that onlyif returns a 0.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L878-L921
| null |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State._run_check_cmd
|
python
|
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
|
Alter the way a successful state run is determined
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L968-L985
| null |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State._load_states
|
python
|
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
|
Read the state loader value and loadup the correct states subsystem
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L993-L1001
| null |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State.load_modules
|
python
|
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
|
Load the modules into the state
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L1003-L1035
|
[
"def _load_states(self):\n '''\n Read the state loader value and loadup the correct states subsystem\n '''\n if self.states_loader == 'thorium':\n self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?\n else:\n self.states = salt.loader.states(self.opts, self.functions, self.utils,\n self.serializers, context=self.state_con, proxy=self.proxy)\n"
] |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State.module_refresh
|
python
|
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
|
Refresh all the modules
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L1037-L1054
|
[
"def load_modules(self, data=None, proxy=None):\n '''\n Load the modules into the state\n '''\n log.info('Loading fresh modules for state activity')\n self.utils = salt.loader.utils(self.opts)\n self.functions = salt.loader.minion_mods(self.opts, self.state_con,\n utils=self.utils,\n proxy=self.proxy)\n if isinstance(data, dict):\n if data.get('provider', False):\n if isinstance(data['provider'], six.string_types):\n providers = [{data['state']: data['provider']}]\n elif isinstance(data['provider'], list):\n providers = data['provider']\n else:\n providers = {}\n for provider in providers:\n for mod in provider:\n funcs = salt.loader.raw_mod(self.opts,\n provider[mod],\n self.functions)\n if funcs:\n for func in funcs:\n f_key = '{0}{1}'.format(\n mod,\n func[func.rindex('.'):]\n )\n self.functions[f_key] = funcs[func]\n self.serializers = salt.loader.serializers(self.opts)\n self._load_states()\n self.rend = salt.loader.render(self.opts, self.functions,\n states=self.states, proxy=self.proxy, context=self.state_con)\n"
] |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State.check_refresh
|
python
|
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
|
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L1056-L1096
|
[
"def _gather_pillar(self):\n '''\n Whenever a state run starts, gather the pillar data fresh\n '''\n if self._pillar_override:\n if self._pillar_enc:\n try:\n self._pillar_override = salt.utils.crypt.decrypt(\n self._pillar_override,\n self._pillar_enc,\n translate_newlines=True,\n renderers=getattr(self, 'rend', None),\n opts=self.opts,\n valid_rend=self.opts['decrypt_pillar_renderers'])\n except Exception as exc:\n log.error('Failed to decrypt pillar override: %s', exc)\n\n if isinstance(self._pillar_override, six.string_types):\n # This can happen if an entire pillar dictionary was passed as\n # a single encrypted string. The override will have been\n # decrypted above, and should now be a stringified dictionary.\n # Use the YAML loader to convert that to a Python dictionary.\n try:\n self._pillar_override = yamlloader.load(\n self._pillar_override,\n Loader=yamlloader.SaltYamlSafeLoader)\n except Exception as exc:\n log.error('Failed to load CLI pillar override')\n log.exception(exc)\n\n if not isinstance(self._pillar_override, dict):\n log.error('Pillar override was not passed as a dictionary')\n self._pillar_override = None\n\n pillar = salt.pillar.get_pillar(\n self.opts,\n self.opts['grains'],\n self.opts['id'],\n self.opts['saltenv'],\n pillar_override=self._pillar_override,\n pillarenv=self.opts.get('pillarenv'))\n return pillar.compile_pillar()\n",
"def module_refresh(self):\n '''\n Refresh all the modules\n '''\n log.debug('Refreshing modules...')\n if self.opts['grains'].get('os') != 'MacOS':\n # In case a package has been installed into the current python\n # process 'site-packages', the 'site' module needs to be reloaded in\n # order for the newly installed package to be importable.\n try:\n reload_module(site)\n except RuntimeError:\n log.error('Error encountered during module reload. Modules were not reloaded.')\n except TypeError:\n log.error('Error encountered during module reload. Modules were not reloaded.')\n self.load_modules()\n if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):\n self.functions['saltutil.refresh_modules']()\n"
] |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State.verify_data
|
python
|
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
|
Verify the data, return an error statement if something is wrong
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L1098-L1186
|
[
"def get_function_argspec(func, is_class_method=None):\n '''\n A small wrapper around getargspec that also supports callable classes\n :param is_class_method: Pass True if you are sure that the function being passed\n is a class method. The reason for this is that on Python 3\n ``inspect.ismethod`` only returns ``True`` for bound methods,\n while on Python 2, it returns ``True`` for bound and unbound\n methods. So, on Python 3, in case of a class method, you'd\n need the class to which the function belongs to be instantiated\n and this is not always wanted.\n '''\n if not callable(func):\n raise TypeError('{0} is not a callable'.format(func))\n\n if six.PY2:\n if is_class_method is True:\n aspec = inspect.getargspec(func)\n del aspec.args[0] # self\n elif inspect.isfunction(func):\n aspec = inspect.getargspec(func)\n elif inspect.ismethod(func):\n aspec = inspect.getargspec(func)\n del aspec.args[0] # self\n elif isinstance(func, object):\n aspec = inspect.getargspec(func.__call__)\n del aspec.args[0] # self\n else:\n raise TypeError(\n 'Cannot inspect argument list for \\'{0}\\''.format(func)\n )\n else:\n if is_class_method is True:\n aspec = _getargspec(func)\n del aspec.args[0] # self\n elif inspect.isfunction(func):\n aspec = _getargspec(func) # pylint: disable=redefined-variable-type\n elif inspect.ismethod(func):\n aspec = _getargspec(func)\n del aspec.args[0] # self\n elif isinstance(func, object):\n aspec = _getargspec(func.__call__)\n del aspec.args[0] # self\n else:\n raise TypeError(\n 'Cannot inspect argument list for \\'{0}\\''.format(func)\n )\n return aspec\n"
] |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State.verify_chunks
|
python
|
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
|
Verify the chunks in a list of low data structures
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L1346-L1353
|
[
"def verify_data(self, data):\n '''\n Verify the data, return an error statement if something is wrong\n '''\n errors = []\n if 'state' not in data:\n errors.append('Missing \"state\" data')\n if 'fun' not in data:\n errors.append('Missing \"fun\" data')\n if 'name' not in data:\n errors.append('Missing \"name\" data')\n if data['name'] and not isinstance(data['name'], six.string_types):\n errors.append(\n 'ID \\'{0}\\' {1}is not formed as a string, but is a {2}'.format(\n data['name'],\n 'in SLS \\'{0}\\' '.format(data['__sls__'])\n if '__sls__' in data else '',\n type(data['name']).__name__\n )\n )\n if errors:\n return errors\n full = data['state'] + '.' + data['fun']\n if full not in self.states:\n if '__sls__' in data:\n errors.append(\n 'State \\'{0}\\' was not found in SLS \\'{1}\\''.format(\n full,\n data['__sls__']\n )\n )\n reason = self.states.missing_fun_string(full)\n if reason:\n errors.append('Reason: {0}'.format(reason))\n else:\n errors.append(\n 'Specified state \\'{0}\\' was not found'.format(\n full\n )\n )\n else:\n # First verify that the parameters are met\n aspec = salt.utils.args.get_function_argspec(self.states[full])\n arglen = 0\n deflen = 0\n if isinstance(aspec.args, list):\n arglen = len(aspec.args)\n if isinstance(aspec.defaults, tuple):\n deflen = len(aspec.defaults)\n for ind in range(arglen - deflen):\n if aspec.args[ind] not in data:\n errors.append(\n 'Missing parameter {0} for state {1}'.format(\n aspec.args[ind],\n full\n )\n )\n # If this chunk has a recursive require, then it will cause a\n # recursive loop when executing, check for it\n reqdec = ''\n if 'require' in data:\n reqdec = 'require'\n if 'watch' in data:\n # Check to see if the service has a mod_watch function, if it does\n # not, then just require\n # to just require extend the require statement with the contents\n # of watch so that the mod_watch function is not called and the\n # requisite capability is still used\n if '{0}.mod_watch'.format(data['state']) not in self.states:\n if 'require' in data:\n data['require'].extend(data.pop('watch'))\n else:\n data['require'] = data.pop('watch')\n reqdec = 'require'\n else:\n reqdec = 'watch'\n if reqdec:\n for req in data[reqdec]:\n reqfirst = next(iter(req))\n if data['state'] == reqfirst:\n if (fnmatch.fnmatch(data['name'], req[reqfirst])\n or fnmatch.fnmatch(data['__id__'], req[reqfirst])):\n err = ('Recursive require detected in SLS {0} for'\n ' require {1} in ID {2}').format(\n data['__sls__'],\n req,\n data['__id__'])\n errors.append(err)\n return errors\n"
] |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State.order_chunks
|
python
|
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
|
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L1355-L1386
| null |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State.compile_high_data
|
python
|
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
|
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L1388-L1452
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n",
"def order_chunks(self, chunks):\n '''\n Sort the chunk list verifying that the chunks follow the order\n specified in the order options.\n '''\n cap = 1\n for chunk in chunks:\n if 'order' in chunk:\n if not isinstance(chunk['order'], int):\n continue\n\n chunk_order = chunk['order']\n if chunk_order > cap - 1 and chunk_order > 0:\n cap = chunk_order + 100\n for chunk in chunks:\n if 'order' not in chunk:\n chunk['order'] = cap\n continue\n\n if not isinstance(chunk['order'], (int, float)):\n if chunk['order'] == 'last':\n chunk['order'] = cap + 1000000\n elif chunk['order'] == 'first':\n chunk['order'] = 0\n else:\n chunk['order'] = cap\n if 'name_order' in chunk:\n chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0\n if chunk['order'] < 0:\n chunk['order'] = cap + 1000000 + chunk['order']\n chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))\n return chunks\n"
] |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State.reconcile_extend
|
python
|
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
|
Pull the extend data and add it to the respective high data
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L1454-L1520
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def find_name(name, state, high):\n '''\n Scan high data for the id referencing the given name and return a list of (IDs, state) tuples that match\n\n Note: if `state` is sls, then we are looking for all IDs that match the given SLS\n '''\n ext_id = []\n if name in high:\n ext_id.append((name, state))\n # if we are requiring an entire SLS, then we need to add ourselves to everything in that SLS\n elif state == 'sls':\n for nid, item in six.iteritems(high):\n if item['__sls__'] == name:\n ext_id.append((nid, next(iter(item))))\n # otherwise we are requiring a single state, lets find it\n else:\n # We need to scan for the name\n for nid in high:\n if state in high[nid]:\n if isinstance(high[nid][state], list):\n for arg in high[nid][state]:\n if not isinstance(arg, dict):\n continue\n if len(arg) != 1:\n continue\n if arg[next(iter(arg))] == name:\n ext_id.append((nid, state))\n return ext_id\n"
] |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State.requisite_in
|
python
|
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
|
Extend the data reference with requisite_in arguments
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L1562-L1787
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def iterkeys(d, **kw):\n return d.iterkeys(**kw)\n",
"def state_args(id_, state, high):\n '''\n Return a set of the arguments passed to the named state\n '''\n args = set()\n if id_ not in high:\n return args\n if state not in high[id_]:\n return args\n for item in high[id_][state]:\n if not isinstance(item, dict):\n continue\n if len(item) != 1:\n continue\n args.add(next(iter(item)))\n return args\n",
"def find_name(name, state, high):\n '''\n Scan high data for the id referencing the given name and return a list of (IDs, state) tuples that match\n\n Note: if `state` is sls, then we are looking for all IDs that match the given SLS\n '''\n ext_id = []\n if name in high:\n ext_id.append((name, state))\n # if we are requiring an entire SLS, then we need to add ourselves to everything in that SLS\n elif state == 'sls':\n for nid, item in six.iteritems(high):\n if item['__sls__'] == name:\n ext_id.append((nid, next(iter(item))))\n # otherwise we are requiring a single state, lets find it\n else:\n # We need to scan for the name\n for nid in high:\n if state in high[nid]:\n if isinstance(high[nid][state], list):\n for arg in high[nid][state]:\n if not isinstance(arg, dict):\n continue\n if len(arg) != 1:\n continue\n if arg[next(iter(arg))] == name:\n ext_id.append((nid, state))\n return ext_id\n",
"def find_sls_ids(sls, high):\n '''\n Scan for all ids in the given sls and return them in a dict; {name: state}\n '''\n ret = []\n for nid, item in six.iteritems(high):\n try:\n sls_tgt = item['__sls__']\n except TypeError:\n if nid != '__exclude__':\n log.error(\n 'Invalid non-dict item \\'%s\\' in high data. Value: %r',\n nid, item\n )\n continue\n else:\n if sls_tgt == sls:\n for st_ in item:\n if st_.startswith('__'):\n continue\n ret.append((nid, st_))\n return ret\n",
"def reconcile_extend(self, high):\n '''\n Pull the extend data and add it to the respective high data\n '''\n errors = []\n if '__extend__' not in high:\n return high, errors\n ext = high.pop('__extend__')\n for ext_chunk in ext:\n for name, body in six.iteritems(ext_chunk):\n if name not in high:\n state_type = next(\n x for x in body if not x.startswith('__')\n )\n # Check for a matching 'name' override in high data\n ids = find_name(name, state_type, high)\n if len(ids) != 1:\n errors.append(\n 'Cannot extend ID \\'{0}\\' in \\'{1}:{2}\\'. It is not '\n 'part of the high state.\\n'\n 'This is likely due to a missing include statement '\n 'or an incorrectly typed ID.\\nEnsure that a '\n 'state with an ID of \\'{0}\\' is available\\nin '\n 'environment \\'{1}\\' and to SLS \\'{2}\\''.format(\n name,\n body.get('__env__', 'base'),\n body.get('__sls__', 'base'))\n )\n continue\n else:\n name = ids[0][0]\n\n for state, run in six.iteritems(body):\n if state.startswith('__'):\n continue\n if state not in high[name]:\n high[name][state] = run\n continue\n # high[name][state] is extended by run, both are lists\n for arg in run:\n update = False\n for hind in range(len(high[name][state])):\n if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):\n # replacing the function, replace the index\n high[name][state].pop(hind)\n high[name][state].insert(hind, arg)\n update = True\n continue\n if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):\n # It is an option, make sure the options match\n argfirst = next(iter(arg))\n if argfirst == next(iter(high[name][state][hind])):\n # If argfirst is a requisite then we must merge\n # our requisite with that of the target state\n if argfirst in STATE_REQUISITE_KEYWORDS:\n high[name][state][hind][argfirst].extend(arg[argfirst])\n # otherwise, its not a requisite and we are just extending (replacing)\n else:\n high[name][state][hind] = arg\n update = True\n if (argfirst == 'name' and\n next(iter(high[name][state][hind])) == 'names'):\n # If names are overwritten by name use the name\n high[name][state][hind] = arg\n if not update:\n high[name][state].append(arg)\n return high, errors\n"
] |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State._call_parallel_target
|
python
|
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
|
The target function to call that will create the parallel thread/process
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L1789-L1830
| null |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State.call_parallel
|
python
|
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
|
Call the state defined in the given cdata in parallel
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L1832-L1854
| null |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State.call
|
python
|
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
|
Call a state directly with the low data structure, verify data
before processing.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L1857-L2100
|
[
"def format_call(fun,\n data,\n initial_ret=None,\n expected_extra_kws=(),\n is_class_method=None):\n '''\n Build the required arguments and keyword arguments required for the passed\n function.\n\n :param fun: The function to get the argspec from\n :param data: A dictionary containing the required data to build the\n arguments and keyword arguments.\n :param initial_ret: The initial return data pre-populated as dictionary or\n None\n :param expected_extra_kws: Any expected extra keyword argument names which\n should not trigger a :ref:`SaltInvocationError`\n :param is_class_method: Pass True if you are sure that the function being passed\n is a class method. The reason for this is that on Python 3\n ``inspect.ismethod`` only returns ``True`` for bound methods,\n while on Python 2, it returns ``True`` for bound and unbound\n methods. So, on Python 3, in case of a class method, you'd\n need the class to which the function belongs to be instantiated\n and this is not always wanted.\n :returns: A dictionary with the function required arguments and keyword\n arguments.\n '''\n ret = initial_ret is not None and initial_ret or {}\n\n ret['args'] = []\n ret['kwargs'] = OrderedDict()\n\n aspec = get_function_argspec(fun, is_class_method=is_class_method)\n\n arg_data = arg_lookup(fun, aspec)\n args = arg_data['args']\n kwargs = arg_data['kwargs']\n\n # Since we WILL be changing the data dictionary, let's change a copy of it\n data = data.copy()\n\n missing_args = []\n\n for key in kwargs:\n try:\n kwargs[key] = data.pop(key)\n except KeyError:\n # Let's leave the default value in place\n pass\n\n while args:\n arg = args.pop(0)\n try:\n ret['args'].append(data.pop(arg))\n except KeyError:\n missing_args.append(arg)\n\n if missing_args:\n used_args_count = len(ret['args']) + len(args)\n args_count = used_args_count + len(missing_args)\n raise SaltInvocationError(\n '{0} takes at least {1} argument{2} ({3} given)'.format(\n fun.__name__,\n args_count,\n args_count > 1 and 's' or '',\n used_args_count\n )\n )\n\n ret['kwargs'].update(kwargs)\n\n if aspec.keywords:\n # The function accepts **kwargs, any non expected extra keyword\n # arguments will made available.\n for key, value in six.iteritems(data):\n if key in expected_extra_kws:\n continue\n ret['kwargs'][key] = value\n\n # No need to check for extra keyword arguments since they are all\n # **kwargs now. Return\n return ret\n\n # Did not return yet? Lets gather any remaining and unexpected keyword\n # arguments\n extra = {}\n for key, value in six.iteritems(data):\n if key in expected_extra_kws:\n continue\n extra[key] = copy.deepcopy(value)\n\n if extra:\n # Found unexpected keyword arguments, raise an error to the user\n if len(extra) == 1:\n msg = '\\'{0[0]}\\' is an invalid keyword argument for \\'{1}\\''.format(\n list(extra.keys()),\n ret.get(\n # In case this is being called for a state module\n 'full',\n # Not a state module, build the name\n '{0}.{1}'.format(fun.__module__, fun.__name__)\n )\n )\n else:\n msg = '{0} and \\'{1}\\' are invalid keyword arguments for \\'{2}\\''.format(\n ', '.join(['\\'{0}\\''.format(e) for e in extra][:-1]),\n list(extra.keys())[-1],\n ret.get(\n # In case this is being called for a state module\n 'full',\n # Not a state module, build the name\n '{0}.{1}'.format(fun.__module__, fun.__name__)\n )\n )\n\n raise SaltInvocationError(msg)\n return ret\n",
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def freeze(obj):\n '''\n Freeze python types by turning them into immutable structures.\n '''\n if isinstance(obj, dict):\n return ImmutableDict(obj)\n if isinstance(obj, list):\n return ImmutableList(obj)\n if isinstance(obj, set):\n return ImmutableSet(obj)\n return obj\n",
"def format_log(ret):\n '''\n Format the state into a log message\n '''\n msg = ''\n if isinstance(ret, dict):\n # Looks like the ret may be a valid state return\n if 'changes' in ret:\n # Yep, looks like a valid state return\n chg = ret['changes']\n if not chg:\n if ret['comment']:\n msg = ret['comment']\n else:\n msg = 'No changes made for {0[name]}'.format(ret)\n elif isinstance(chg, dict):\n if 'diff' in chg:\n if isinstance(chg['diff'], six.string_types):\n msg = 'File changed:\\n{0}'.format(chg['diff'])\n if all([isinstance(x, dict) for x in six.itervalues(chg)]):\n if all([('old' in x and 'new' in x)\n for x in six.itervalues(chg)]):\n msg = 'Made the following changes:\\n'\n for pkg in chg:\n old = chg[pkg]['old']\n if not old and old not in (False, None):\n old = 'absent'\n new = chg[pkg]['new']\n if not new and new not in (False, None):\n new = 'absent'\n # This must be able to handle unicode as some package names contain\n # non-ascii characters like \"Français\" or \"Español\". See Issue #33605.\n msg += '\\'{0}\\' changed from \\'{1}\\' to \\'{2}\\'\\n'.format(pkg, old, new)\n if not msg:\n msg = six.text_type(ret['changes'])\n if ret['result'] is True or ret['result'] is None:\n log.info(msg)\n else:\n log.error(msg)\n else:\n # catch unhandled data\n log.info(six.text_type(ret))\n",
"def mock_ret(cdata):\n '''\n Returns a mocked return dict with information about the run, without\n executing the state function\n '''\n # As this is expanded it should be sent into the execution module\n # layer or it should be turned into a standalone loader system\n if cdata['args']:\n name = cdata['args'][0]\n else:\n name = cdata['kwargs']['name']\n return {'name': name,\n 'comment': 'Not called, mocked',\n 'changes': {},\n 'result': True}\n",
"def _run_check(self, low_data):\n '''\n Check that unless doesn't return 0, and that onlyif returns a 0.\n '''\n ret = {'result': False, 'comment': []}\n cmd_opts = {}\n\n if 'shell' in self.opts['grains']:\n cmd_opts['shell'] = self.opts['grains'].get('shell')\n\n if 'onlyif' in low_data:\n _ret = self._run_check_onlyif(low_data, cmd_opts)\n ret['result'] = _ret['result']\n ret['comment'].append(_ret['comment'])\n if 'skip_watch' in _ret:\n ret['skip_watch'] = _ret['skip_watch']\n\n if 'unless' in low_data:\n _ret = self._run_check_unless(low_data, cmd_opts)\n # If either result is True, the returned result should be True\n ret['result'] = _ret['result'] or ret['result']\n ret['comment'].append(_ret['comment'])\n if 'skip_watch' in _ret:\n # If either result is True, the returned result should be True\n ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']\n\n return ret\n",
"def _run_check_cmd(self, low_data):\n '''\n Alter the way a successful state run is determined\n '''\n ret = {'result': False}\n cmd_opts = {}\n if 'shell' in self.opts['grains']:\n cmd_opts['shell'] = self.opts['grains'].get('shell')\n for entry in low_data['check_cmd']:\n cmd = self.functions['cmd.retcode'](\n entry, ignore_retcode=True, python_shell=True, **cmd_opts)\n log.debug('Last command return code: %s', cmd)\n if cmd == 0 and ret['result'] is False:\n ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})\n elif cmd != 0:\n ret.update({'comment': 'check_cmd determined the state failed', 'result': False})\n return ret\n return ret\n",
"def load_modules(self, data=None, proxy=None):\n '''\n Load the modules into the state\n '''\n log.info('Loading fresh modules for state activity')\n self.utils = salt.loader.utils(self.opts)\n self.functions = salt.loader.minion_mods(self.opts, self.state_con,\n utils=self.utils,\n proxy=self.proxy)\n if isinstance(data, dict):\n if data.get('provider', False):\n if isinstance(data['provider'], six.string_types):\n providers = [{data['state']: data['provider']}]\n elif isinstance(data['provider'], list):\n providers = data['provider']\n else:\n providers = {}\n for provider in providers:\n for mod in provider:\n funcs = salt.loader.raw_mod(self.opts,\n provider[mod],\n self.functions)\n if funcs:\n for func in funcs:\n f_key = '{0}{1}'.format(\n mod,\n func[func.rindex('.'):]\n )\n self.functions[f_key] = funcs[func]\n self.serializers = salt.loader.serializers(self.opts)\n self._load_states()\n self.rend = salt.loader.render(self.opts, self.functions,\n states=self.states, proxy=self.proxy, context=self.state_con)\n",
"def check_refresh(self, data, ret):\n '''\n Check to see if the modules for this state instance need to be updated,\n only update if the state is a file or a package and if it changed\n something. If the file function is managed check to see if the file is a\n possible module type, e.g. a python, pyx, or .so. Always refresh if the\n function is recurse, since that can lay down anything.\n '''\n _reload_modules = False\n if data.get('reload_grains', False):\n log.debug('Refreshing grains...')\n self.opts['grains'] = salt.loader.grains(self.opts)\n _reload_modules = True\n\n if data.get('reload_pillar', False):\n log.debug('Refreshing pillar...')\n self.opts['pillar'] = self._gather_pillar()\n _reload_modules = True\n\n if not ret['changes']:\n if data.get('force_reload_modules', False):\n self.module_refresh()\n return\n\n if data.get('reload_modules', False) or _reload_modules:\n # User explicitly requests a reload\n self.module_refresh()\n return\n\n if data['state'] == 'file':\n if data['fun'] == 'managed':\n if data['name'].endswith(\n ('.py', '.pyx', '.pyo', '.pyc', '.so')):\n self.module_refresh()\n elif data['fun'] == 'recurse':\n self.module_refresh()\n elif data['fun'] == 'symlink':\n if 'bin' in data['name']:\n self.module_refresh()\n elif data['state'] in ('pkg', 'ports'):\n self.module_refresh()\n",
"def verify_data(self, data):\n '''\n Verify the data, return an error statement if something is wrong\n '''\n errors = []\n if 'state' not in data:\n errors.append('Missing \"state\" data')\n if 'fun' not in data:\n errors.append('Missing \"fun\" data')\n if 'name' not in data:\n errors.append('Missing \"name\" data')\n if data['name'] and not isinstance(data['name'], six.string_types):\n errors.append(\n 'ID \\'{0}\\' {1}is not formed as a string, but is a {2}'.format(\n data['name'],\n 'in SLS \\'{0}\\' '.format(data['__sls__'])\n if '__sls__' in data else '',\n type(data['name']).__name__\n )\n )\n if errors:\n return errors\n full = data['state'] + '.' + data['fun']\n if full not in self.states:\n if '__sls__' in data:\n errors.append(\n 'State \\'{0}\\' was not found in SLS \\'{1}\\''.format(\n full,\n data['__sls__']\n )\n )\n reason = self.states.missing_fun_string(full)\n if reason:\n errors.append('Reason: {0}'.format(reason))\n else:\n errors.append(\n 'Specified state \\'{0}\\' was not found'.format(\n full\n )\n )\n else:\n # First verify that the parameters are met\n aspec = salt.utils.args.get_function_argspec(self.states[full])\n arglen = 0\n deflen = 0\n if isinstance(aspec.args, list):\n arglen = len(aspec.args)\n if isinstance(aspec.defaults, tuple):\n deflen = len(aspec.defaults)\n for ind in range(arglen - deflen):\n if aspec.args[ind] not in data:\n errors.append(\n 'Missing parameter {0} for state {1}'.format(\n aspec.args[ind],\n full\n )\n )\n # If this chunk has a recursive require, then it will cause a\n # recursive loop when executing, check for it\n reqdec = ''\n if 'require' in data:\n reqdec = 'require'\n if 'watch' in data:\n # Check to see if the service has a mod_watch function, if it does\n # not, then just require\n # to just require extend the require statement with the contents\n # of watch so that the mod_watch function is not called and the\n # requisite capability is still used\n if '{0}.mod_watch'.format(data['state']) not in self.states:\n if 'require' in data:\n data['require'].extend(data.pop('watch'))\n else:\n data['require'] = data.pop('watch')\n reqdec = 'require'\n else:\n reqdec = 'watch'\n if reqdec:\n for req in data[reqdec]:\n reqfirst = next(iter(req))\n if data['state'] == reqfirst:\n if (fnmatch.fnmatch(data['name'], req[reqfirst])\n or fnmatch.fnmatch(data['__id__'], req[reqfirst])):\n err = ('Recursive require detected in SLS {0} for'\n ' require {1} in ID {2}').format(\n data['__sls__'],\n req,\n data['__id__'])\n errors.append(err)\n return errors\n"
] |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State.format_slots
|
python
|
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
|
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L2159-L2209
|
[
"def decode(data, encoding=None, errors='strict', keep=False,\n normalize=False, preserve_dict_class=False, preserve_tuples=False,\n to_str=False):\n '''\n Generic function which will decode whichever type is passed, if necessary.\n Optionally use to_str=True to ensure strings are str types and not unicode\n on Python 2.\n\n If `strict` is True, and `keep` is False, and we fail to decode, a\n UnicodeDecodeError will be raised. Passing `keep` as True allows for the\n original value to silently be returned in cases where decoding fails. This\n can be useful for cases where the data passed to this function is likely to\n contain binary blobs, such as in the case of cp.recv.\n\n If `normalize` is True, then unicodedata.normalize() will be used to\n normalize unicode strings down to a single code point per glyph. It is\n recommended not to normalize unless you know what you're doing. For\n instance, if `data` contains a dictionary, it is possible that normalizing\n will lead to data loss because the following two strings will normalize to\n the same value:\n\n - u'\\\\u044f\\\\u0438\\\\u0306\\\\u0446\\\\u0430.txt'\n - u'\\\\u044f\\\\u0439\\\\u0446\\\\u0430.txt'\n\n One good use case for normalization is in the test suite. For example, on\n some platforms such as Mac OS, os.listdir() will produce the first of the\n two strings above, in which \"й\" is represented as two code points (i.e. one\n for the base character, and one for the breve mark). Normalizing allows for\n a more reliable test case.\n '''\n _decode_func = salt.utils.stringutils.to_unicode \\\n if not to_str \\\n else salt.utils.stringutils.to_str\n if isinstance(data, Mapping):\n return decode_dict(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, list):\n return decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n elif isinstance(data, tuple):\n return decode_tuple(data, encoding, errors, keep, normalize,\n preserve_dict_class, to_str) \\\n if preserve_tuples \\\n else decode_list(data, encoding, errors, keep, normalize,\n preserve_dict_class, preserve_tuples, to_str)\n else:\n try:\n data = _decode_func(data, encoding, errors, normalize)\n except TypeError:\n # to_unicode raises a TypeError when input is not a\n # string/bytestring/bytearray. This is expected and simply means we\n # are going to leave the value as-is.\n pass\n except UnicodeDecodeError:\n if not keep:\n raise\n return data\n",
"def __eval_slot(self, slot):\n log.debug('Evaluating slot: %s', slot)\n fmt = slot.split(':', 2)\n if len(fmt) != 3:\n log.warning('Malformed slot: %s', slot)\n return slot\n if fmt[1] != 'salt':\n log.warning('Malformed slot: %s', slot)\n log.warning('Only execution modules are currently supported in slots. This means slot '\n 'should start with \"__slot__:salt:\"')\n return slot\n fun, args, kwargs = salt.utils.args.parse_function(fmt[2])\n if not fun or fun not in self.functions:\n log.warning('Malformed slot: %s', slot)\n log.warning('Execution module should be specified in a function call format: '\n 'test.arg(\\'arg\\', kw=\\'kwarg\\')')\n return slot\n log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)\n slot_return = self.functions[fun](*args, **kwargs)\n\n # Given input __slot__:salt:test.arg(somekey=\"value\").not.exist ~ /appended\n # slot_text should be __slot...).not.exist\n # append_data should be ~ /appended\n slot_text = fmt[2].split('~')[0]\n append_data = fmt[2].split('~', 1)[1:]\n log.debug('slot_text: %s', slot_text)\n log.debug('append_data: %s', append_data)\n\n # Support parsing slot dict response\n # return_get should result in a kwargs.nested.dict path by getting\n # everything after first closing paren: )\n return_get = None\n try:\n return_get = slot_text[slot_text.rindex(')')+1:]\n except ValueError:\n pass\n if return_get:\n #remove first period\n return_get = return_get.split('.', 1)[1].strip()\n log.debug('Searching slot result %s for %s', slot_return, return_get)\n slot_return = salt.utils.data.traverse_dict_and_list(slot_return,\n return_get,\n default=None,\n delimiter='.'\n )\n\n if append_data:\n if isinstance(slot_return, six.string_types):\n # Append text to slot string result\n append_data = ' '.join(append_data).strip()\n log.debug('appending to slot result: %s', append_data)\n slot_return += append_data\n else:\n log.error('Ignoring slot append, slot result is not a string')\n\n return slot_return\n"
] |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State.verify_retry_data
|
python
|
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
|
verifies the specified retry data
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L2211-L2246
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n"
] |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State.call_chunks
|
python
|
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
|
Iterate over a list of chunks and call them, checking for requires.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L2248-L2295
|
[
"def _gen_tag(low):\n '''\n Generate the running dict tag string from the low data structure\n '''\n return '{0[state]}_|-{0[__id__]}_|-{0[name]}_|-{0[fun]}'.format(low)\n",
"def check_failhard(self, low, running):\n '''\n Check if the low data chunk should send a failhard signal\n '''\n tag = _gen_tag(low)\n if self.opts.get('test', False):\n return False\n if low.get('failhard', self.opts['failhard']) and tag in running:\n if running[tag]['result'] is None:\n return False\n return not running[tag]['result']\n return False\n",
"def check_pause(self, low):\n '''\n Check to see if this low chunk has been paused\n '''\n if not self.jid:\n # Can't pause on salt-ssh since we can't track continuous state\n return\n pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)\n start = time.time()\n if os.path.isfile(pause_path):\n try:\n while True:\n tries = 0\n with salt.utils.files.fopen(pause_path, 'rb') as fp_:\n try:\n pdat = msgpack_deserialize(fp_.read())\n except msgpack.UnpackValueError:\n # Reading race condition\n if tries > 10:\n # Break out if there are a ton of read errors\n return\n tries += 1\n time.sleep(1)\n continue\n id_ = low['__id__']\n key = ''\n if id_ in pdat:\n key = id_\n elif '__all__' in pdat:\n key = '__all__'\n if key:\n if 'duration' in pdat[key]:\n now = time.time()\n if now - start > pdat[key]['duration']:\n return 'run'\n if 'kill' in pdat[key]:\n return 'kill'\n else:\n return 'run'\n time.sleep(1)\n except Exception as exc:\n log.error('Failed to read in pause data for file located at: %s', pause_path)\n return 'run'\n return 'run'\n",
"def reconcile_procs(self, running):\n '''\n Check the running dict for processes and resolve them\n '''\n retset = set()\n for tag in running:\n proc = running[tag].get('proc')\n if proc:\n if not proc.is_alive():\n ret_cache = os.path.join(\n self.opts['cachedir'],\n self.jid,\n salt.utils.hashutils.sha1_digest(tag))\n if not os.path.isfile(ret_cache):\n ret = {'result': False,\n 'comment': 'Parallel process failed to return',\n 'name': running[tag]['name'],\n 'changes': {}}\n try:\n with salt.utils.files.fopen(ret_cache, 'rb') as fp_:\n ret = msgpack_deserialize(fp_.read())\n except (OSError, IOError):\n ret = {'result': False,\n 'comment': 'Parallel cache failure',\n 'name': running[tag]['name'],\n 'changes': {}}\n running[tag].update(ret)\n running[tag].pop('proc')\n else:\n retset.add(False)\n return False not in retset\n",
"def call_chunk(self, low, running, chunks):\n '''\n Check if a chunk has any requires, execute the requires and then\n the chunk\n '''\n low = self._mod_aggregate(low, running, chunks)\n self._mod_init(low)\n tag = _gen_tag(low)\n if not low.get('prerequired'):\n self.active.add(tag)\n requisites = ['require',\n 'require_any',\n 'watch',\n 'watch_any',\n 'prereq',\n 'onfail',\n 'onfail_any',\n 'onchanges',\n 'onchanges_any']\n if not low.get('__prereq__'):\n requisites.append('prerequired')\n status, reqs = self.check_requisite(low, running, chunks, pre=True)\n else:\n status, reqs = self.check_requisite(low, running, chunks)\n if status == 'unmet':\n lost = {}\n reqs = []\n for requisite in requisites:\n lost[requisite] = []\n if requisite not in low:\n continue\n for req in low[requisite]:\n if isinstance(req, six.string_types):\n req = {'id': req}\n req = trim_req(req)\n found = False\n req_key = next(iter(req))\n req_val = req[req_key]\n for chunk in chunks:\n if req_val is None:\n continue\n if req_key == 'sls':\n # Allow requisite tracking of entire sls files\n if fnmatch.fnmatch(chunk['__sls__'], req_val):\n if requisite == 'prereq':\n chunk['__prereq__'] = True\n reqs.append(chunk)\n found = True\n continue\n if (fnmatch.fnmatch(chunk['name'], req_val) or\n fnmatch.fnmatch(chunk['__id__'], req_val)):\n if req_key == 'id' or chunk['state'] == req_key:\n if requisite == 'prereq':\n chunk['__prereq__'] = True\n elif requisite == 'prerequired':\n chunk['__prerequired__'] = True\n reqs.append(chunk)\n found = True\n if not found:\n lost[requisite].append(req)\n if lost['require'] or lost['watch'] or lost['prereq'] \\\n or lost['onfail'] or lost['onchanges'] \\\n or lost.get('prerequired'):\n comment = 'The following requisites were not found:\\n'\n for requisite, lreqs in six.iteritems(lost):\n if not lreqs:\n continue\n comment += \\\n '{0}{1}:\\n'.format(' ' * 19, requisite)\n for lreq in lreqs:\n req_key = next(iter(lreq))\n req_val = lreq[req_key]\n comment += \\\n '{0}{1}: {2}\\n'.format(' ' * 23, req_key, req_val)\n if low.get('__prereq__'):\n run_dict = self.pre\n else:\n run_dict = running\n start_time, duration = _calculate_fake_duration()\n run_dict[tag] = {'changes': {},\n 'result': False,\n 'duration': duration,\n 'start_time': start_time,\n 'comment': comment,\n '__run_num__': self.__run_num,\n '__sls__': low['__sls__']}\n self.__run_num += 1\n self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))\n return running\n for chunk in reqs:\n # Check to see if the chunk has been run, only run it if\n # it has not been run already\n ctag = _gen_tag(chunk)\n if ctag not in running:\n if ctag in self.active:\n if chunk.get('__prerequired__'):\n # Prereq recusive, run this chunk with prereq on\n if tag not in self.pre:\n low['__prereq__'] = True\n self.pre[ctag] = self.call(low, chunks, running)\n return running\n else:\n return running\n elif ctag not in running:\n log.error('Recursive requisite found')\n running[tag] = {\n 'changes': {},\n 'result': False,\n 'comment': 'Recursive requisite found',\n '__run_num__': self.__run_num,\n '__sls__': low['__sls__']}\n self.__run_num += 1\n self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))\n return running\n running = self.call_chunk(chunk, running, chunks)\n if self.check_failhard(chunk, running):\n running['__FAILHARD__'] = True\n return running\n if low.get('__prereq__'):\n status, reqs = self.check_requisite(low, running, chunks)\n self.pre[tag] = self.call(low, chunks, running)\n if not self.pre[tag]['changes'] and status == 'change':\n self.pre[tag]['changes'] = {'watch': 'watch'}\n self.pre[tag]['result'] = None\n else:\n running = self.call_chunk(low, running, chunks)\n if self.check_failhard(chunk, running):\n running['__FAILHARD__'] = True\n return running\n elif status == 'met':\n if low.get('__prereq__'):\n self.pre[tag] = self.call(low, chunks, running)\n else:\n running[tag] = self.call(low, chunks, running)\n elif status == 'fail':\n # if the requisite that failed was due to a prereq on this low state\n # show the normal error\n if tag in self.pre:\n running[tag] = self.pre[tag]\n running[tag]['__run_num__'] = self.__run_num\n running[tag]['__sls__'] = low['__sls__']\n # otherwise the failure was due to a requisite down the chain\n else:\n # determine what the requisite failures where, and return\n # a nice error message\n failed_requisites = set()\n # look at all requisite types for a failure\n for req_lows in six.itervalues(reqs):\n for req_low in req_lows:\n req_tag = _gen_tag(req_low)\n req_ret = self.pre.get(req_tag, running.get(req_tag))\n # if there is no run output for the requisite it\n # can't be the failure\n if req_ret is None:\n continue\n # If the result was False (not None) it was a failure\n if req_ret['result'] is False:\n # use SLS.ID for the key-- so its easier to find\n key = '{sls}.{_id}'.format(sls=req_low['__sls__'],\n _id=req_low['__id__'])\n failed_requisites.add(key)\n\n _cmt = 'One or more requisite failed: {0}'.format(\n ', '.join(six.text_type(i) for i in failed_requisites)\n )\n start_time, duration = _calculate_fake_duration()\n running[tag] = {\n 'changes': {},\n 'result': False,\n 'duration': duration,\n 'start_time': start_time,\n 'comment': _cmt,\n '__run_num__': self.__run_num,\n '__sls__': low['__sls__']\n }\n self.pre[tag] = running[tag]\n self.__run_num += 1\n elif status == 'change' and not low.get('__prereq__'):\n ret = self.call(low, chunks, running)\n if not ret['changes'] and not ret.get('skip_watch', False):\n low = low.copy()\n low['sfun'] = low['fun']\n low['fun'] = 'mod_watch'\n low['__reqs__'] = reqs\n ret = self.call(low, chunks, running)\n running[tag] = ret\n elif status == 'pre':\n start_time, duration = _calculate_fake_duration()\n pre_ret = {'changes': {},\n 'result': True,\n 'duration': duration,\n 'start_time': start_time,\n 'comment': 'No changes detected',\n '__run_num__': self.__run_num,\n '__sls__': low['__sls__']}\n running[tag] = pre_ret\n self.pre[tag] = pre_ret\n self.__run_num += 1\n elif status == 'onfail':\n start_time, duration = _calculate_fake_duration()\n running[tag] = {'changes': {},\n 'result': True,\n 'duration': duration,\n 'start_time': start_time,\n 'comment': 'State was not run because onfail req did not change',\n '__state_ran__': False,\n '__run_num__': self.__run_num,\n '__sls__': low['__sls__']}\n self.__run_num += 1\n elif status == 'onchanges':\n start_time, duration = _calculate_fake_duration()\n running[tag] = {'changes': {},\n 'result': True,\n 'duration': duration,\n 'start_time': start_time,\n 'comment': 'State was not run because none of the onchanges reqs changed',\n '__state_ran__': False,\n '__run_num__': self.__run_num,\n '__sls__': low['__sls__']}\n self.__run_num += 1\n else:\n if low.get('__prereq__'):\n self.pre[tag] = self.call(low, chunks, running)\n else:\n running[tag] = self.call(low, chunks, running)\n if tag in running:\n running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])\n self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))\n return running\n"
] |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State.check_failhard
|
python
|
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
|
Check if the low data chunk should send a failhard signal
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L2297-L2308
|
[
"def _gen_tag(low):\n '''\n Generate the running dict tag string from the low data structure\n '''\n return '{0[state]}_|-{0[__id__]}_|-{0[name]}_|-{0[fun]}'.format(low)\n"
] |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State.check_pause
|
python
|
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
|
Check to see if this low chunk has been paused
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L2310-L2353
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def _deserialize(stream_or_string, **options):\n _fail()\n",
"def _deserialize(stream_or_string, **options):\n try:\n options.setdefault('use_list', True)\n options.setdefault('encoding', 'utf-8')\n return salt.utils.msgpack.loads(stream_or_string,\n _msgpack_module=msgpack,\n **options)\n except Exception as error:\n raise DeserializationError(error)\n",
"def _deserialize(stream_or_string, **options):\n options.setdefault('use_list', True)\n try:\n obj = salt.utils.msgpack.loads(stream_or_string,\n _msgpack_module=msgpack)\n return _decoder(obj)\n except Exception as error:\n raise DeserializationError(error)\n"
] |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State.reconcile_procs
|
python
|
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
|
Check the running dict for processes and resolve them
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L2355-L2385
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def _deserialize(stream_or_string, **options):\n _fail()\n",
"def _deserialize(stream_or_string, **options):\n try:\n options.setdefault('use_list', True)\n options.setdefault('encoding', 'utf-8')\n return salt.utils.msgpack.loads(stream_or_string,\n _msgpack_module=msgpack,\n **options)\n except Exception as error:\n raise DeserializationError(error)\n",
"def _deserialize(stream_or_string, **options):\n options.setdefault('use_list', True)\n try:\n obj = salt.utils.msgpack.loads(stream_or_string,\n _msgpack_module=msgpack)\n return _decoder(obj)\n except Exception as error:\n raise DeserializationError(error)\n",
"def sha1_digest(instr):\n '''\n Generate an sha1 hash of a given string.\n '''\n if six.PY3:\n b = salt.utils.stringutils.to_bytes(instr)\n return hashlib.sha1(b).hexdigest()\n return hashlib.sha1(instr).hexdigest()\n"
] |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State.check_requisite
|
python
|
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
|
Look into the running data to check the status of all requisite
states
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L2387-L2572
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def _gen_tag(low):\n '''\n Generate the running dict tag string from the low data structure\n '''\n return '{0[state]}_|-{0[__id__]}_|-{0[name]}_|-{0[fun]}'.format(low)\n",
"def trim_req(req):\n '''\n Trim any function off of a requisite\n '''\n reqfirst = next(iter(req))\n if '.' in reqfirst:\n return {reqfirst.split('.')[0]: req[reqfirst]}\n return req\n",
"def reconcile_procs(self, running):\n '''\n Check the running dict for processes and resolve them\n '''\n retset = set()\n for tag in running:\n proc = running[tag].get('proc')\n if proc:\n if not proc.is_alive():\n ret_cache = os.path.join(\n self.opts['cachedir'],\n self.jid,\n salt.utils.hashutils.sha1_digest(tag))\n if not os.path.isfile(ret_cache):\n ret = {'result': False,\n 'comment': 'Parallel process failed to return',\n 'name': running[tag]['name'],\n 'changes': {}}\n try:\n with salt.utils.files.fopen(ret_cache, 'rb') as fp_:\n ret = msgpack_deserialize(fp_.read())\n except (OSError, IOError):\n ret = {'result': False,\n 'comment': 'Parallel cache failure',\n 'name': running[tag]['name'],\n 'changes': {}}\n running[tag].update(ret)\n running[tag].pop('proc')\n else:\n retset.add(False)\n return False not in retset\n"
] |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State.event
|
python
|
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
|
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L2574-L2611
| null |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State.call_chunk
|
python
|
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
|
Check if a chunk has any requires, execute the requires and then
the chunk
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L2613-L2841
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def itervalues(d, **kw):\n return d.itervalues(**kw)\n",
"def _gen_tag(low):\n '''\n Generate the running dict tag string from the low data structure\n '''\n return '{0[state]}_|-{0[__id__]}_|-{0[name]}_|-{0[fun]}'.format(low)\n",
"def _calculate_fake_duration():\n '''\n Generate a NULL duration for when states do not run\n but we want the results to be consistent.\n '''\n utc_start_time = datetime.datetime.utcnow()\n local_start_time = utc_start_time - \\\n (datetime.datetime.utcnow() - datetime.datetime.now())\n utc_finish_time = datetime.datetime.utcnow()\n start_time = local_start_time.time().isoformat()\n delta = (utc_finish_time - utc_start_time)\n # duration in milliseconds.microseconds\n duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0\n\n return start_time, duration\n",
"def trim_req(req):\n '''\n Trim any function off of a requisite\n '''\n reqfirst = next(iter(req))\n if '.' in reqfirst:\n return {reqfirst.split('.')[0]: req[reqfirst]}\n return req\n",
"def _mod_init(self, low):\n '''\n Check the module initialization function, if this is the first run\n of a state package that has a mod_init function, then execute the\n mod_init function in the state module.\n '''\n # ensure that the module is loaded\n try:\n self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106\n except KeyError:\n return\n minit = '{0}.mod_init'.format(low['state'])\n if low['state'] not in self.mod_init:\n if minit in self.states._dict:\n mret = self.states[minit](low)\n if not mret:\n return\n self.mod_init.add(low['state'])\n",
"def _mod_aggregate(self, low, running, chunks):\n '''\n Execute the aggregation systems to runtime modify the low chunk\n '''\n agg_opt = self.functions['config.option']('state_aggregate')\n if 'aggregate' in low:\n agg_opt = low['aggregate']\n if agg_opt is True:\n agg_opt = [low['state']]\n elif not isinstance(agg_opt, list):\n return low\n if low['state'] in agg_opt and not low.get('__agg__'):\n agg_fun = '{0}.mod_aggregate'.format(low['state'])\n if agg_fun in self.states:\n try:\n low = self.states[agg_fun](low, chunks, running)\n low['__agg__'] = True\n except TypeError:\n log.error('Failed to execute aggregate for state %s', low['state'])\n return low\n",
"def check_failhard(self, low, running):\n '''\n Check if the low data chunk should send a failhard signal\n '''\n tag = _gen_tag(low)\n if self.opts.get('test', False):\n return False\n if low.get('failhard', self.opts['failhard']) and tag in running:\n if running[tag]['result'] is None:\n return False\n return not running[tag]['result']\n return False\n",
"def check_requisite(self, low, running, chunks, pre=False):\n '''\n Look into the running data to check the status of all requisite\n states\n '''\n disabled_reqs = self.opts.get('disabled_requisites', [])\n if not isinstance(disabled_reqs, list):\n disabled_reqs = [disabled_reqs]\n present = False\n # If mod_watch is not available make it a require\n if 'watch' in low:\n if '{0}.mod_watch'.format(low['state']) not in self.states:\n if 'require' in low:\n low['require'].extend(low.pop('watch'))\n else:\n low['require'] = low.pop('watch')\n else:\n present = True\n if 'watch_any' in low:\n if '{0}.mod_watch'.format(low['state']) not in self.states:\n if 'require_any' in low:\n low['require_any'].extend(low.pop('watch_any'))\n else:\n low['require_any'] = low.pop('watch_any')\n else:\n present = True\n if 'require' in low:\n present = True\n if 'require_any' in low:\n present = True\n if 'prerequired' in low:\n present = True\n if 'prereq' in low:\n present = True\n if 'onfail' in low:\n present = True\n if 'onfail_any' in low:\n present = True\n if 'onfail_all' in low:\n present = True\n if 'onchanges' in low:\n present = True\n if 'onchanges_any' in low:\n present = True\n if not present:\n return 'met', ()\n self.reconcile_procs(running)\n reqs = {\n 'require': [],\n 'require_any': [],\n 'watch': [],\n 'watch_any': [],\n 'prereq': [],\n 'onfail': [],\n 'onfail_any': [],\n 'onfail_all': [],\n 'onchanges': [],\n 'onchanges_any': []}\n if pre:\n reqs['prerequired'] = []\n for r_state in reqs:\n if r_state in low and low[r_state] is not None:\n if r_state in disabled_reqs:\n log.warning('The %s requisite has been disabled, Ignoring.', r_state)\n continue\n for req in low[r_state]:\n if isinstance(req, six.string_types):\n req = {'id': req}\n req = trim_req(req)\n found = False\n for chunk in chunks:\n req_key = next(iter(req))\n req_val = req[req_key]\n if req_val is None:\n continue\n if req_key == 'sls':\n # Allow requisite tracking of entire sls files\n if fnmatch.fnmatch(chunk['__sls__'], req_val):\n found = True\n reqs[r_state].append(chunk)\n continue\n try:\n if isinstance(req_val, six.string_types):\n if (fnmatch.fnmatch(chunk['name'], req_val) or\n fnmatch.fnmatch(chunk['__id__'], req_val)):\n if req_key == 'id' or chunk['state'] == req_key:\n found = True\n reqs[r_state].append(chunk)\n else:\n raise KeyError\n except KeyError as exc:\n raise SaltRenderError(\n 'Could not locate requisite of [{0}] present in state with name [{1}]'.format(\n req_key, chunk['name']))\n except TypeError:\n # On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,\n # however on Python 3 it will raise a TypeError\n # This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite\n raise SaltRenderError(\n 'Could not locate requisite of [{0}] present in state with name [{1}]'.format(\n req_key, chunk['name']))\n if not found:\n return 'unmet', ()\n fun_stats = set()\n for r_state, chunks in six.iteritems(reqs):\n req_stats = set()\n if r_state.startswith('prereq') and not r_state.startswith('prerequired'):\n run_dict = self.pre\n else:\n run_dict = running\n\n while True:\n if self.reconcile_procs(run_dict):\n break\n time.sleep(0.01)\n\n for chunk in chunks:\n tag = _gen_tag(chunk)\n if tag not in run_dict:\n req_stats.add('unmet')\n continue\n if r_state.startswith('onfail'):\n if run_dict[tag]['result'] is True:\n req_stats.add('onfail') # At least one state is OK\n continue\n else:\n if run_dict[tag]['result'] is False:\n req_stats.add('fail')\n continue\n if r_state.startswith('onchanges'):\n if not run_dict[tag]['changes']:\n req_stats.add('onchanges')\n else:\n req_stats.add('onchangesmet')\n continue\n if r_state.startswith('watch') and run_dict[tag]['changes']:\n req_stats.add('change')\n continue\n if r_state.startswith('prereq') and run_dict[tag]['result'] is None:\n if not r_state.startswith('prerequired'):\n req_stats.add('premet')\n if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:\n if not r_state.startswith('prerequired'):\n req_stats.add('pre')\n else:\n if run_dict[tag].get('__state_ran__', True):\n req_stats.add('met')\n if r_state.endswith('_any') or r_state == 'onfail':\n if 'met' in req_stats or 'change' in req_stats:\n if 'fail' in req_stats:\n req_stats.remove('fail')\n if 'onchangesmet' in req_stats:\n if 'onchanges' in req_stats:\n req_stats.remove('onchanges')\n if 'fail' in req_stats:\n req_stats.remove('fail')\n if 'onfail' in req_stats:\n # a met requisite in this case implies a success\n if 'met' in req_stats:\n req_stats.remove('onfail')\n if r_state.endswith('_all'):\n if 'onfail' in req_stats:\n # a met requisite in this case implies a failure\n if 'met' in req_stats:\n req_stats.remove('met')\n fun_stats.update(req_stats)\n\n if 'unmet' in fun_stats:\n status = 'unmet'\n elif 'fail' in fun_stats:\n status = 'fail'\n elif 'pre' in fun_stats:\n if 'premet' in fun_stats:\n status = 'met'\n else:\n status = 'pre'\n elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:\n status = 'onfail'\n elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:\n status = 'onchanges'\n elif 'change' in fun_stats:\n status = 'change'\n else:\n status = 'met'\n\n return status, reqs\n",
"def event(self, chunk_ret, length, fire_event=False):\n '''\n Fire an event on the master bus\n\n If `fire_event` is set to True an event will be sent with the\n chunk name in the tag and the chunk result in the event data.\n\n If `fire_event` is set to a string such as `mystate/is/finished`,\n an event will be sent with the string added to the tag and the chunk\n result in the event data.\n\n If the `state_events` is set to True in the config, then after the\n chunk is evaluated an event will be set up to the master with the\n results.\n '''\n if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):\n if not self.opts.get('master_uri'):\n ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(\n self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)\n else:\n ev_func = self.functions['event.fire_master']\n\n ret = {'ret': chunk_ret}\n if fire_event is True:\n tag = salt.utils.event.tagify(\n [self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'\n )\n elif isinstance(fire_event, six.string_types):\n tag = salt.utils.event.tagify(\n [self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'\n )\n else:\n tag = salt.utils.event.tagify(\n [self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'\n )\n ret['len'] = length\n preload = {'jid': self.jid}\n ev_func(ret, tag, preload=preload)\n",
"def call_chunk(self, low, running, chunks):\n '''\n Check if a chunk has any requires, execute the requires and then\n the chunk\n '''\n low = self._mod_aggregate(low, running, chunks)\n self._mod_init(low)\n tag = _gen_tag(low)\n if not low.get('prerequired'):\n self.active.add(tag)\n requisites = ['require',\n 'require_any',\n 'watch',\n 'watch_any',\n 'prereq',\n 'onfail',\n 'onfail_any',\n 'onchanges',\n 'onchanges_any']\n if not low.get('__prereq__'):\n requisites.append('prerequired')\n status, reqs = self.check_requisite(low, running, chunks, pre=True)\n else:\n status, reqs = self.check_requisite(low, running, chunks)\n if status == 'unmet':\n lost = {}\n reqs = []\n for requisite in requisites:\n lost[requisite] = []\n if requisite not in low:\n continue\n for req in low[requisite]:\n if isinstance(req, six.string_types):\n req = {'id': req}\n req = trim_req(req)\n found = False\n req_key = next(iter(req))\n req_val = req[req_key]\n for chunk in chunks:\n if req_val is None:\n continue\n if req_key == 'sls':\n # Allow requisite tracking of entire sls files\n if fnmatch.fnmatch(chunk['__sls__'], req_val):\n if requisite == 'prereq':\n chunk['__prereq__'] = True\n reqs.append(chunk)\n found = True\n continue\n if (fnmatch.fnmatch(chunk['name'], req_val) or\n fnmatch.fnmatch(chunk['__id__'], req_val)):\n if req_key == 'id' or chunk['state'] == req_key:\n if requisite == 'prereq':\n chunk['__prereq__'] = True\n elif requisite == 'prerequired':\n chunk['__prerequired__'] = True\n reqs.append(chunk)\n found = True\n if not found:\n lost[requisite].append(req)\n if lost['require'] or lost['watch'] or lost['prereq'] \\\n or lost['onfail'] or lost['onchanges'] \\\n or lost.get('prerequired'):\n comment = 'The following requisites were not found:\\n'\n for requisite, lreqs in six.iteritems(lost):\n if not lreqs:\n continue\n comment += \\\n '{0}{1}:\\n'.format(' ' * 19, requisite)\n for lreq in lreqs:\n req_key = next(iter(lreq))\n req_val = lreq[req_key]\n comment += \\\n '{0}{1}: {2}\\n'.format(' ' * 23, req_key, req_val)\n if low.get('__prereq__'):\n run_dict = self.pre\n else:\n run_dict = running\n start_time, duration = _calculate_fake_duration()\n run_dict[tag] = {'changes': {},\n 'result': False,\n 'duration': duration,\n 'start_time': start_time,\n 'comment': comment,\n '__run_num__': self.__run_num,\n '__sls__': low['__sls__']}\n self.__run_num += 1\n self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))\n return running\n for chunk in reqs:\n # Check to see if the chunk has been run, only run it if\n # it has not been run already\n ctag = _gen_tag(chunk)\n if ctag not in running:\n if ctag in self.active:\n if chunk.get('__prerequired__'):\n # Prereq recusive, run this chunk with prereq on\n if tag not in self.pre:\n low['__prereq__'] = True\n self.pre[ctag] = self.call(low, chunks, running)\n return running\n else:\n return running\n elif ctag not in running:\n log.error('Recursive requisite found')\n running[tag] = {\n 'changes': {},\n 'result': False,\n 'comment': 'Recursive requisite found',\n '__run_num__': self.__run_num,\n '__sls__': low['__sls__']}\n self.__run_num += 1\n self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))\n return running\n running = self.call_chunk(chunk, running, chunks)\n if self.check_failhard(chunk, running):\n running['__FAILHARD__'] = True\n return running\n if low.get('__prereq__'):\n status, reqs = self.check_requisite(low, running, chunks)\n self.pre[tag] = self.call(low, chunks, running)\n if not self.pre[tag]['changes'] and status == 'change':\n self.pre[tag]['changes'] = {'watch': 'watch'}\n self.pre[tag]['result'] = None\n else:\n running = self.call_chunk(low, running, chunks)\n if self.check_failhard(chunk, running):\n running['__FAILHARD__'] = True\n return running\n elif status == 'met':\n if low.get('__prereq__'):\n self.pre[tag] = self.call(low, chunks, running)\n else:\n running[tag] = self.call(low, chunks, running)\n elif status == 'fail':\n # if the requisite that failed was due to a prereq on this low state\n # show the normal error\n if tag in self.pre:\n running[tag] = self.pre[tag]\n running[tag]['__run_num__'] = self.__run_num\n running[tag]['__sls__'] = low['__sls__']\n # otherwise the failure was due to a requisite down the chain\n else:\n # determine what the requisite failures where, and return\n # a nice error message\n failed_requisites = set()\n # look at all requisite types for a failure\n for req_lows in six.itervalues(reqs):\n for req_low in req_lows:\n req_tag = _gen_tag(req_low)\n req_ret = self.pre.get(req_tag, running.get(req_tag))\n # if there is no run output for the requisite it\n # can't be the failure\n if req_ret is None:\n continue\n # If the result was False (not None) it was a failure\n if req_ret['result'] is False:\n # use SLS.ID for the key-- so its easier to find\n key = '{sls}.{_id}'.format(sls=req_low['__sls__'],\n _id=req_low['__id__'])\n failed_requisites.add(key)\n\n _cmt = 'One or more requisite failed: {0}'.format(\n ', '.join(six.text_type(i) for i in failed_requisites)\n )\n start_time, duration = _calculate_fake_duration()\n running[tag] = {\n 'changes': {},\n 'result': False,\n 'duration': duration,\n 'start_time': start_time,\n 'comment': _cmt,\n '__run_num__': self.__run_num,\n '__sls__': low['__sls__']\n }\n self.pre[tag] = running[tag]\n self.__run_num += 1\n elif status == 'change' and not low.get('__prereq__'):\n ret = self.call(low, chunks, running)\n if not ret['changes'] and not ret.get('skip_watch', False):\n low = low.copy()\n low['sfun'] = low['fun']\n low['fun'] = 'mod_watch'\n low['__reqs__'] = reqs\n ret = self.call(low, chunks, running)\n running[tag] = ret\n elif status == 'pre':\n start_time, duration = _calculate_fake_duration()\n pre_ret = {'changes': {},\n 'result': True,\n 'duration': duration,\n 'start_time': start_time,\n 'comment': 'No changes detected',\n '__run_num__': self.__run_num,\n '__sls__': low['__sls__']}\n running[tag] = pre_ret\n self.pre[tag] = pre_ret\n self.__run_num += 1\n elif status == 'onfail':\n start_time, duration = _calculate_fake_duration()\n running[tag] = {'changes': {},\n 'result': True,\n 'duration': duration,\n 'start_time': start_time,\n 'comment': 'State was not run because onfail req did not change',\n '__state_ran__': False,\n '__run_num__': self.__run_num,\n '__sls__': low['__sls__']}\n self.__run_num += 1\n elif status == 'onchanges':\n start_time, duration = _calculate_fake_duration()\n running[tag] = {'changes': {},\n 'result': True,\n 'duration': duration,\n 'start_time': start_time,\n 'comment': 'State was not run because none of the onchanges reqs changed',\n '__state_ran__': False,\n '__run_num__': self.__run_num,\n '__sls__': low['__sls__']}\n self.__run_num += 1\n else:\n if low.get('__prereq__'):\n self.pre[tag] = self.call(low, chunks, running)\n else:\n running[tag] = self.call(low, chunks, running)\n if tag in running:\n running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])\n self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))\n return running\n"
] |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State.call_listen
|
python
|
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
|
Find all of the listen routines and call the associated mod_watch runs
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L2843-L2914
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def _l_tag(name, id_):\n low = {'name': 'listen_{0}'.format(name),\n '__id__': 'listen_{0}'.format(id_),\n 'state': 'Listen_Error',\n 'fun': 'Listen_Error'}\n return _gen_tag(low)\n",
"def call_chunks(self, chunks):\n '''\n Iterate over a list of chunks and call them, checking for requires.\n '''\n # Check for any disabled states\n disabled = {}\n if 'state_runs_disabled' in self.opts['grains']:\n for low in chunks[:]:\n state_ = '{0}.{1}'.format(low['state'], low['fun'])\n for pat in self.opts['grains']['state_runs_disabled']:\n if fnmatch.fnmatch(state_, pat):\n comment = (\n 'The state function \"{0}\" is currently disabled by \"{1}\", '\n 'to re-enable, run state.enable {1}.'\n ).format(\n state_,\n pat,\n )\n _tag = _gen_tag(low)\n disabled[_tag] = {'changes': {},\n 'result': False,\n 'comment': comment,\n '__run_num__': self.__run_num,\n '__sls__': low['__sls__']}\n self.__run_num += 1\n chunks.remove(low)\n break\n running = {}\n for low in chunks:\n if '__FAILHARD__' in running:\n running.pop('__FAILHARD__')\n return running\n tag = _gen_tag(low)\n if tag not in running:\n # Check if this low chunk is paused\n action = self.check_pause(low)\n if action == 'kill':\n break\n running = self.call_chunk(low, running, chunks)\n if self.check_failhard(low, running):\n return running\n self.active = set()\n while True:\n if self.reconcile_procs(running):\n break\n time.sleep(0.01)\n ret = dict(list(disabled.items()) + list(running.items()))\n return ret\n"
] |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State.inject_default_call
|
python
|
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
|
Sets .call function to a state, if not there.
:param high:
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L2916-L2936
| null |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State.call_high
|
python
|
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
|
Process a high data call and ensure the defined states.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L2938-L2986
|
[
"def verify_high(self, high):\n '''\n Verify that the high data is viable and follows the data structure\n '''\n errors = []\n if not isinstance(high, dict):\n errors.append('High data is not a dictionary and is invalid')\n reqs = OrderedDict()\n for name, body in six.iteritems(high):\n try:\n if name.startswith('__'):\n continue\n except AttributeError:\n pass\n if not isinstance(name, six.string_types):\n errors.append(\n 'ID \\'{0}\\' in SLS \\'{1}\\' is not formed as a string, but '\n 'is a {2}. It may need to be quoted.'.format(\n name, body['__sls__'], type(name).__name__)\n )\n if not isinstance(body, dict):\n err = ('The type {0} in {1} is not formatted as a dictionary'\n .format(name, body))\n errors.append(err)\n continue\n for state in body:\n if state.startswith('__'):\n continue\n if body[state] is None:\n errors.append(\n 'ID \\'{0}\\' in SLS \\'{1}\\' contains a short declaration '\n '({2}) with a trailing colon. When not passing any '\n 'arguments to a state, the colon must be omitted.'\n .format(name, body['__sls__'], state)\n )\n continue\n if not isinstance(body[state], list):\n errors.append(\n 'State \\'{0}\\' in SLS \\'{1}\\' is not formed as a list'\n .format(name, body['__sls__'])\n )\n else:\n fun = 0\n if '.' in state:\n fun += 1\n for arg in body[state]:\n if isinstance(arg, six.string_types):\n fun += 1\n if ' ' in arg.strip():\n errors.append(('The function \"{0}\" in state '\n '\"{1}\" in SLS \"{2}\" has '\n 'whitespace, a function with whitespace is '\n 'not supported, perhaps this is an argument '\n 'that is missing a \":\"').format(\n arg,\n name,\n body['__sls__']))\n elif isinstance(arg, dict):\n # The arg is a dict, if the arg is require or\n # watch, it must be a list.\n #\n # Add the requires to the reqs dict and check them\n # all for recursive requisites.\n argfirst = next(iter(arg))\n if argfirst == 'names':\n if not isinstance(arg[argfirst], list):\n errors.append(\n 'The \\'names\\' argument in state '\n '\\'{0}\\' in SLS \\'{1}\\' needs to be '\n 'formed as a list'\n .format(name, body['__sls__'])\n )\n if argfirst in ('require', 'watch', 'prereq', 'onchanges'):\n if not isinstance(arg[argfirst], list):\n errors.append(\n 'The {0} statement in state \\'{1}\\' in '\n 'SLS \\'{2}\\' needs to be formed as a '\n 'list'.format(argfirst,\n name,\n body['__sls__'])\n )\n # It is a list, verify that the members of the\n # list are all single key dicts.\n else:\n reqs[name] = OrderedDict(state=state)\n for req in arg[argfirst]:\n if isinstance(req, six.string_types):\n req = {'id': req}\n if not isinstance(req, dict):\n err = ('Requisite declaration {0}'\n ' in SLS {1} is not formed as a'\n ' single key dictionary').format(\n req,\n body['__sls__'])\n errors.append(err)\n continue\n req_key = next(iter(req))\n req_val = req[req_key]\n if '.' in req_key:\n errors.append(\n 'Invalid requisite type \\'{0}\\' '\n 'in state \\'{1}\\', in SLS '\n '\\'{2}\\'. Requisite types must '\n 'not contain dots, did you '\n 'mean \\'{3}\\'?'.format(\n req_key,\n name,\n body['__sls__'],\n req_key[:req_key.find('.')]\n )\n )\n if not ishashable(req_val):\n errors.append((\n 'Illegal requisite \"{0}\", '\n 'please check your syntax.\\n'\n ).format(req_val))\n continue\n\n # Check for global recursive requisites\n reqs[name][req_val] = req_key\n # I am going beyond 80 chars on\n # purpose, this is just too much\n # of a pain to deal with otherwise\n if req_val in reqs:\n if name in reqs[req_val]:\n if reqs[req_val][name] == state:\n if reqs[req_val]['state'] == reqs[name][req_val]:\n err = ('A recursive '\n 'requisite was found, SLS '\n '\"{0}\" ID \"{1}\" ID \"{2}\"'\n ).format(\n body['__sls__'],\n name,\n req_val\n )\n errors.append(err)\n # Make sure that there is only one key in the\n # dict\n if len(list(arg)) != 1:\n errors.append(\n 'Multiple dictionaries defined in '\n 'argument of state \\'{0}\\' in SLS \\'{1}\\''\n .format(name, body['__sls__'])\n )\n if not fun:\n if state == 'require' or state == 'watch':\n continue\n errors.append(\n 'No function declared in state \\'{0}\\' in SLS \\'{1}\\''\n .format(state, body['__sls__'])\n )\n elif fun > 1:\n errors.append(\n 'Too many functions declared in state \\'{0}\\' in '\n 'SLS \\'{1}\\''.format(state, body['__sls__'])\n )\n return errors\n",
"def compile_high_data(self, high, orchestration_jid=None):\n '''\n \"Compile\" the high data as it is retrieved from the CLI or YAML into\n the individual state executor structures\n '''\n chunks = []\n for name, body in six.iteritems(high):\n if name.startswith('__'):\n continue\n for state, run in six.iteritems(body):\n funcs = set()\n names = []\n if state.startswith('__'):\n continue\n chunk = OrderedDict()\n chunk['state'] = state\n chunk['name'] = name\n if orchestration_jid is not None:\n chunk['__orchestration_jid__'] = orchestration_jid\n if '__sls__' in body:\n chunk['__sls__'] = body['__sls__']\n if '__env__' in body:\n chunk['__env__'] = body['__env__']\n chunk['__id__'] = name\n for arg in run:\n if isinstance(arg, six.string_types):\n funcs.add(arg)\n continue\n if isinstance(arg, dict):\n for key, val in six.iteritems(arg):\n if key == 'names':\n for _name in val:\n if _name not in names:\n names.append(_name)\n elif key == 'state':\n # Don't pass down a state override\n continue\n elif (key == 'name' and\n not isinstance(val, six.string_types)):\n # Invalid name, fall back to ID\n chunk[key] = name\n else:\n chunk[key] = val\n if names:\n name_order = 1\n for entry in names:\n live = copy.deepcopy(chunk)\n if isinstance(entry, dict):\n low_name = next(six.iterkeys(entry))\n live['name'] = low_name\n list(map(live.update, entry[low_name]))\n else:\n live['name'] = entry\n live['name_order'] = name_order\n name_order += 1\n for fun in funcs:\n live['fun'] = fun\n chunks.append(live)\n else:\n live = copy.deepcopy(chunk)\n for fun in funcs:\n live['fun'] = fun\n chunks.append(live)\n chunks = self.order_chunks(chunks)\n return chunks\n",
"def reconcile_extend(self, high):\n '''\n Pull the extend data and add it to the respective high data\n '''\n errors = []\n if '__extend__' not in high:\n return high, errors\n ext = high.pop('__extend__')\n for ext_chunk in ext:\n for name, body in six.iteritems(ext_chunk):\n if name not in high:\n state_type = next(\n x for x in body if not x.startswith('__')\n )\n # Check for a matching 'name' override in high data\n ids = find_name(name, state_type, high)\n if len(ids) != 1:\n errors.append(\n 'Cannot extend ID \\'{0}\\' in \\'{1}:{2}\\'. It is not '\n 'part of the high state.\\n'\n 'This is likely due to a missing include statement '\n 'or an incorrectly typed ID.\\nEnsure that a '\n 'state with an ID of \\'{0}\\' is available\\nin '\n 'environment \\'{1}\\' and to SLS \\'{2}\\''.format(\n name,\n body.get('__env__', 'base'),\n body.get('__sls__', 'base'))\n )\n continue\n else:\n name = ids[0][0]\n\n for state, run in six.iteritems(body):\n if state.startswith('__'):\n continue\n if state not in high[name]:\n high[name][state] = run\n continue\n # high[name][state] is extended by run, both are lists\n for arg in run:\n update = False\n for hind in range(len(high[name][state])):\n if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):\n # replacing the function, replace the index\n high[name][state].pop(hind)\n high[name][state].insert(hind, arg)\n update = True\n continue\n if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):\n # It is an option, make sure the options match\n argfirst = next(iter(arg))\n if argfirst == next(iter(high[name][state][hind])):\n # If argfirst is a requisite then we must merge\n # our requisite with that of the target state\n if argfirst in STATE_REQUISITE_KEYWORDS:\n high[name][state][hind][argfirst].extend(arg[argfirst])\n # otherwise, its not a requisite and we are just extending (replacing)\n else:\n high[name][state][hind] = arg\n update = True\n if (argfirst == 'name' and\n next(iter(high[name][state][hind])) == 'names'):\n # If names are overwritten by name use the name\n high[name][state][hind] = arg\n if not update:\n high[name][state].append(arg)\n return high, errors\n",
"def apply_exclude(self, high):\n '''\n Read in the __exclude__ list and remove all excluded objects from the\n high data\n '''\n if '__exclude__' not in high:\n return high\n ex_sls = set()\n ex_id = set()\n exclude = high.pop('__exclude__')\n for exc in exclude:\n if isinstance(exc, six.string_types):\n # The exclude statement is a string, assume it is an sls\n ex_sls.add(exc)\n if isinstance(exc, dict):\n # Explicitly declared exclude\n if len(exc) != 1:\n continue\n key = next(six.iterkeys(exc))\n if key == 'sls':\n ex_sls.add(exc['sls'])\n elif key == 'id':\n ex_id.add(exc['id'])\n # Now the excludes have been simplified, use them\n if ex_sls:\n # There are sls excludes, find the associated ids\n for name, body in six.iteritems(high):\n if name.startswith('__'):\n continue\n sls = body.get('__sls__', '')\n if not sls:\n continue\n for ex_ in ex_sls:\n if fnmatch.fnmatch(sls, ex_):\n ex_id.add(name)\n for id_ in ex_id:\n if id_ in high:\n high.pop(id_)\n return high\n",
"def requisite_in(self, high):\n '''\n Extend the data reference with requisite_in arguments\n '''\n req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}\n req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})\n extend = {}\n errors = []\n disabled_reqs = self.opts.get('disabled_requisites', [])\n if not isinstance(disabled_reqs, list):\n disabled_reqs = [disabled_reqs]\n for id_, body in six.iteritems(high):\n if not isinstance(body, dict):\n continue\n for state, run in six.iteritems(body):\n if state.startswith('__'):\n continue\n for arg in run:\n if isinstance(arg, dict):\n # It is not a function, verify that the arg is a\n # requisite in statement\n if not arg:\n # Empty arg dict\n # How did we get this far?\n continue\n # Split out the components\n key = next(iter(arg))\n if key not in req_in:\n continue\n if key in disabled_reqs:\n log.warning('The %s requisite has been disabled, Ignoring.', key)\n continue\n rkey = key.split('_')[0]\n items = arg[key]\n if isinstance(items, dict):\n # Formatted as a single req_in\n for _state, name in six.iteritems(items):\n\n # Not a use requisite_in\n found = False\n if name not in extend:\n extend[name] = OrderedDict()\n if '.' in _state:\n errors.append(\n 'Invalid requisite in {0}: {1} for '\n '{2}, in SLS \\'{3}\\'. Requisites must '\n 'not contain dots, did you mean \\'{4}\\'?'\n .format(\n rkey,\n _state,\n name,\n body['__sls__'],\n _state[:_state.find('.')]\n )\n )\n _state = _state.split('.')[0]\n if _state not in extend[name]:\n extend[name][_state] = []\n extend[name]['__env__'] = body['__env__']\n extend[name]['__sls__'] = body['__sls__']\n for ind in range(len(extend[name][_state])):\n if next(iter(\n extend[name][_state][ind])) == rkey:\n # Extending again\n extend[name][_state][ind][rkey].append(\n {state: id_}\n )\n found = True\n if found:\n continue\n # The rkey is not present yet, create it\n extend[name][_state].append(\n {rkey: [{state: id_}]}\n )\n\n if isinstance(items, list):\n # Formed as a list of requisite additions\n hinges = []\n for ind in items:\n if not isinstance(ind, dict):\n # Malformed req_in\n if ind in high:\n _ind_high = [x for x\n in high[ind]\n if not x.startswith('__')]\n ind = {_ind_high[0]: ind}\n else:\n found = False\n for _id in iter(high):\n for state in [state for state\n in iter(high[_id])\n if not state.startswith('__')]:\n for j in iter(high[_id][state]):\n if isinstance(j, dict) and 'name' in j:\n if j['name'] == ind:\n ind = {state: _id}\n found = True\n if not found:\n continue\n if not ind:\n continue\n pstate = next(iter(ind))\n pname = ind[pstate]\n if pstate == 'sls':\n # Expand hinges here\n hinges = find_sls_ids(pname, high)\n else:\n hinges.append((pname, pstate))\n if '.' in pstate:\n errors.append(\n 'Invalid requisite in {0}: {1} for '\n '{2}, in SLS \\'{3}\\'. Requisites must '\n 'not contain dots, did you mean \\'{4}\\'?'\n .format(\n rkey,\n pstate,\n pname,\n body['__sls__'],\n pstate[:pstate.find('.')]\n )\n )\n pstate = pstate.split(\".\")[0]\n for tup in hinges:\n name, _state = tup\n if key == 'prereq_in':\n # Add prerequired to origin\n if id_ not in extend:\n extend[id_] = OrderedDict()\n if state not in extend[id_]:\n extend[id_][state] = []\n extend[id_][state].append(\n {'prerequired': [{_state: name}]}\n )\n if key == 'prereq':\n # Add prerequired to prereqs\n ext_ids = find_name(name, _state, high)\n for ext_id, _req_state in ext_ids:\n if ext_id not in extend:\n extend[ext_id] = OrderedDict()\n if _req_state not in extend[ext_id]:\n extend[ext_id][_req_state] = []\n extend[ext_id][_req_state].append(\n {'prerequired': [{state: id_}]}\n )\n continue\n if key == 'use_in':\n # Add the running states args to the\n # use_in states\n ext_ids = find_name(name, _state, high)\n for ext_id, _req_state in ext_ids:\n if not ext_id:\n continue\n ext_args = state_args(ext_id, _state, high)\n if ext_id not in extend:\n extend[ext_id] = OrderedDict()\n if _req_state not in extend[ext_id]:\n extend[ext_id][_req_state] = []\n ignore_args = req_in_all.union(ext_args)\n for arg in high[id_][state]:\n if not isinstance(arg, dict):\n continue\n if len(arg) != 1:\n continue\n if next(iter(arg)) in ignore_args:\n continue\n # Don't use name or names\n if next(six.iterkeys(arg)) == 'name':\n continue\n if next(six.iterkeys(arg)) == 'names':\n continue\n extend[ext_id][_req_state].append(arg)\n continue\n if key == 'use':\n # Add the use state's args to the\n # running state\n ext_ids = find_name(name, _state, high)\n for ext_id, _req_state in ext_ids:\n if not ext_id:\n continue\n loc_args = state_args(id_, state, high)\n if id_ not in extend:\n extend[id_] = OrderedDict()\n if state not in extend[id_]:\n extend[id_][state] = []\n ignore_args = req_in_all.union(loc_args)\n for arg in high[ext_id][_req_state]:\n if not isinstance(arg, dict):\n continue\n if len(arg) != 1:\n continue\n if next(iter(arg)) in ignore_args:\n continue\n # Don't use name or names\n if next(six.iterkeys(arg)) == 'name':\n continue\n if next(six.iterkeys(arg)) == 'names':\n continue\n extend[id_][state].append(arg)\n continue\n found = False\n if name not in extend:\n extend[name] = OrderedDict()\n if _state not in extend[name]:\n extend[name][_state] = []\n extend[name]['__env__'] = body['__env__']\n extend[name]['__sls__'] = body['__sls__']\n for ind in range(len(extend[name][_state])):\n if next(iter(\n extend[name][_state][ind])) == rkey:\n # Extending again\n extend[name][_state][ind][rkey].append(\n {state: id_}\n )\n found = True\n if found:\n continue\n # The rkey is not present yet, create it\n extend[name][_state].append(\n {rkey: [{state: id_}]}\n )\n high['__extend__'] = []\n for key, val in six.iteritems(extend):\n high['__extend__'].append({key: val})\n req_in_high, req_in_errors = self.reconcile_extend(high)\n errors.extend(req_in_errors)\n return req_in_high, errors\n",
"def call_chunks(self, chunks):\n '''\n Iterate over a list of chunks and call them, checking for requires.\n '''\n # Check for any disabled states\n disabled = {}\n if 'state_runs_disabled' in self.opts['grains']:\n for low in chunks[:]:\n state_ = '{0}.{1}'.format(low['state'], low['fun'])\n for pat in self.opts['grains']['state_runs_disabled']:\n if fnmatch.fnmatch(state_, pat):\n comment = (\n 'The state function \"{0}\" is currently disabled by \"{1}\", '\n 'to re-enable, run state.enable {1}.'\n ).format(\n state_,\n pat,\n )\n _tag = _gen_tag(low)\n disabled[_tag] = {'changes': {},\n 'result': False,\n 'comment': comment,\n '__run_num__': self.__run_num,\n '__sls__': low['__sls__']}\n self.__run_num += 1\n chunks.remove(low)\n break\n running = {}\n for low in chunks:\n if '__FAILHARD__' in running:\n running.pop('__FAILHARD__')\n return running\n tag = _gen_tag(low)\n if tag not in running:\n # Check if this low chunk is paused\n action = self.check_pause(low)\n if action == 'kill':\n break\n running = self.call_chunk(low, running, chunks)\n if self.check_failhard(low, running):\n return running\n self.active = set()\n while True:\n if self.reconcile_procs(running):\n break\n time.sleep(0.01)\n ret = dict(list(disabled.items()) + list(running.items()))\n return ret\n",
"def call_listen(self, chunks, running):\n '''\n Find all of the listen routines and call the associated mod_watch runs\n '''\n listeners = []\n crefs = {}\n for chunk in chunks:\n crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk\n if 'listen' in chunk:\n listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})\n if 'listen_in' in chunk:\n for l_in in chunk['listen_in']:\n for key, val in six.iteritems(l_in):\n listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})\n mod_watchers = []\n errors = {}\n for l_dict in listeners:\n for key, val in six.iteritems(l_dict):\n for listen_to in val:\n if not isinstance(listen_to, dict):\n found = False\n for chunk in chunks:\n if chunk['__id__'] == listen_to or \\\n chunk['name'] == listen_to:\n listen_to = {chunk['state']: chunk['__id__']}\n found = True\n if not found:\n continue\n for lkey, lval in six.iteritems(listen_to):\n if not any(lkey == cref[0] and lval in cref for cref in crefs):\n rerror = {_l_tag(lkey, lval):\n {\n 'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),\n 'name': 'listen_{0}:{1}'.format(lkey, lval),\n 'result': False,\n 'changes': {}\n }}\n errors.update(rerror)\n continue\n to_tags = [\n _gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref\n ]\n for to_tag in to_tags:\n if to_tag not in running:\n continue\n if running[to_tag]['changes']:\n if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):\n rerror = {_l_tag(key[0], key[1]):\n {'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),\n 'name': 'listen_{0}:{1}'.format(key[0], key[1]),\n 'result': False,\n 'changes': {}}}\n errors.update(rerror)\n continue\n\n new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]\n for chunk in new_chunks:\n low = chunk.copy()\n low['sfun'] = chunk['fun']\n low['fun'] = 'mod_watch'\n low['__id__'] = 'listener_{0}'.format(low['__id__'])\n for req in STATE_REQUISITE_KEYWORDS:\n if req in low:\n low.pop(req)\n mod_watchers.append(low)\n ret = self.call_chunks(mod_watchers)\n running.update(ret)\n for err in errors:\n errors[err]['__run_num__'] = self.__run_num\n self.__run_num += 1\n running.update(errors)\n return running\n",
"def inject_default_call(self, high):\n '''\n Sets .call function to a state, if not there.\n\n :param high:\n :return:\n '''\n for chunk in high:\n state = high[chunk]\n if not isinstance(state, collections.Mapping):\n continue\n for state_ref in state:\n needs_default = True\n if not isinstance(state[state_ref], list):\n continue\n for argset in state[state_ref]:\n if isinstance(argset, six.string_types):\n needs_default = False\n break\n if needs_default:\n state[state_ref].insert(-1, '__call__')\n",
"def _cleanup_accumulator_data():\n accum_data_path = os.path.join(\n get_accumulator_dir(self.opts['cachedir']),\n self.instance_id\n )\n try:\n os.remove(accum_data_path)\n log.debug('Deleted accumulator data file %s', accum_data_path)\n except OSError:\n log.debug('File %s does not exist, no need to cleanup', accum_data_path)\n"
] |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State.call_template
|
python
|
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
|
Enforce the states in a template
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L3067-L3081
|
[
"def compile_template(template,\n renderers,\n default,\n blacklist,\n whitelist,\n saltenv='base',\n sls='',\n input_data='',\n **kwargs):\n '''\n Take the path to a template and return the high data structure\n derived from the template.\n\n Helpers:\n\n :param mask_value:\n Mask value for debugging purposes (prevent sensitive information etc)\n example: \"mask_value=\"pass*\". All \"passwd\", \"password\", \"pass\" will\n be masked (as text).\n '''\n\n # if any error occurs, we return an empty dictionary\n ret = {}\n\n log.debug('compile template: %s', template)\n\n if 'env' in kwargs:\n # \"env\" is not supported; Use \"saltenv\".\n kwargs.pop('env')\n\n if template != ':string:':\n # Template was specified incorrectly\n if not isinstance(template, six.string_types):\n log.error('Template was specified incorrectly: %s', template)\n return ret\n # Template does not exist\n if not os.path.isfile(template):\n log.error('Template does not exist: %s', template)\n return ret\n # Template is an empty file\n if salt.utils.files.is_empty(template):\n log.debug('Template is an empty file: %s', template)\n return ret\n\n with codecs.open(template, encoding=SLS_ENCODING) as ifile:\n # data input to the first render function in the pipe\n input_data = ifile.read()\n if not input_data.strip():\n # Template is nothing but whitespace\n log.error('Template is nothing but whitespace: %s', template)\n return ret\n\n # Get the list of render funcs in the render pipe line.\n render_pipe = template_shebang(template, renderers, default, blacklist, whitelist, input_data)\n\n windows_newline = '\\r\\n' in input_data\n\n input_data = StringIO(input_data)\n for render, argline in render_pipe:\n if salt.utils.stringio.is_readable(input_data):\n input_data.seek(0) # pylint: disable=no-member\n render_kwargs = dict(renderers=renderers, tmplpath=template)\n render_kwargs.update(kwargs)\n if argline:\n render_kwargs['argline'] = argline\n start = time.time()\n ret = render(input_data, saltenv, sls, **render_kwargs)\n log.profile(\n 'Time (in seconds) to render \\'%s\\' using \\'%s\\' renderer: %s',\n template,\n render.__module__.split('.')[-1],\n time.time() - start\n )\n if ret is None:\n # The file is empty or is being written elsewhere\n time.sleep(0.01)\n ret = render(input_data, saltenv, sls, **render_kwargs)\n input_data = ret\n if log.isEnabledFor(logging.GARBAGE): # pylint: disable=no-member\n # If ret is not a StringIO (which means it was rendered using\n # yaml, mako, or another engine which renders to a data\n # structure) we don't want to log this.\n if salt.utils.stringio.is_readable(ret):\n log.debug('Rendered data from file: %s:\\n%s', template,\n salt.utils.sanitizers.mask_args_value(salt.utils.data.decode(ret.read()),\n kwargs.get('mask_value'))) # pylint: disable=no-member\n ret.seek(0) # pylint: disable=no-member\n\n # Preserve newlines from original template\n if windows_newline:\n if salt.utils.stringio.is_readable(ret):\n is_stringio = True\n contents = ret.read()\n else:\n is_stringio = False\n contents = ret\n\n if isinstance(contents, six.string_types):\n if '\\r\\n' not in contents:\n contents = contents.replace('\\n', '\\r\\n')\n ret = StringIO(contents) if is_stringio else contents\n else:\n if is_stringio:\n ret.seek(0)\n return ret\n",
"def call_high(self, high, orchestration_jid=None):\n '''\n Process a high data call and ensure the defined states.\n '''\n self.inject_default_call(high)\n errors = []\n # If there is extension data reconcile it\n high, ext_errors = self.reconcile_extend(high)\n errors.extend(ext_errors)\n errors.extend(self.verify_high(high))\n if errors:\n return errors\n high, req_in_errors = self.requisite_in(high)\n errors.extend(req_in_errors)\n high = self.apply_exclude(high)\n # Verify that the high data is structurally sound\n if errors:\n return errors\n # Compile and verify the raw chunks\n chunks = self.compile_high_data(high, orchestration_jid)\n\n # If there are extensions in the highstate, process them and update\n # the low data chunks\n if errors:\n return errors\n ret = self.call_chunks(chunks)\n ret = self.call_listen(chunks, ret)\n\n def _cleanup_accumulator_data():\n accum_data_path = os.path.join(\n get_accumulator_dir(self.opts['cachedir']),\n self.instance_id\n )\n try:\n os.remove(accum_data_path)\n log.debug('Deleted accumulator data file %s', accum_data_path)\n except OSError:\n log.debug('File %s does not exist, no need to cleanup', accum_data_path)\n _cleanup_accumulator_data()\n if self.jid is not None:\n pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)\n if os.path.isfile(pause_path):\n try:\n os.remove(pause_path)\n except OSError:\n # File is not present, all is well\n pass\n\n return ret\n",
"def render_template(self, high, template):\n errors = []\n if not high:\n return high, errors\n\n if not isinstance(high, dict):\n errors.append(\n 'Template {0} does not render to a dictionary'.format(template)\n )\n return high, errors\n\n invalid_items = ('include', 'exclude', 'extends')\n for item in invalid_items:\n if item in high:\n errors.append(\n 'The \\'{0}\\' declaration found on \\'{1}\\' is invalid when '\n 'rendering single templates'.format(item, template)\n )\n return high, errors\n\n for name in high:\n if not isinstance(high[name], dict):\n if isinstance(high[name], six.string_types):\n # Is this is a short state, it needs to be padded\n if '.' in high[name]:\n comps = high[name].split('.')\n high[name] = {\n # '__sls__': template,\n # '__env__': None,\n comps[0]: [comps[1]]\n }\n continue\n\n errors.append(\n 'ID {0} in template {1} is not a dictionary'.format(\n name, template\n )\n )\n continue\n skeys = set()\n for key in sorted(high[name]):\n if key.startswith('_'):\n continue\n if high[name][key] is None:\n errors.append(\n 'ID \\'{0}\\' in template {1} contains a short '\n 'declaration ({2}) with a trailing colon. When not '\n 'passing any arguments to a state, the colon must be '\n 'omitted.'.format(name, template, key)\n )\n continue\n if not isinstance(high[name][key], list):\n continue\n if '.' in key:\n comps = key.split('.')\n # Salt doesn't support state files such as:\n #\n # /etc/redis/redis.conf:\n # file.managed:\n # - user: redis\n # - group: redis\n # - mode: 644\n # file.comment:\n # - regex: ^requirepass\n if comps[0] in skeys:\n errors.append(\n 'ID \\'{0}\\' in template \\'{1}\\' contains multiple '\n 'state declarations of the same type'\n .format(name, template)\n )\n continue\n high[name][comps[0]] = high[name].pop(key)\n high[name][comps[0]].append(comps[1])\n skeys.add(comps[0])\n continue\n skeys.add(key)\n\n return high, errors\n"
] |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
State.call_template_str
|
python
|
def call_template_str(self, template):
'''
Enforce the states in a template, pass the template as a string
'''
high = compile_template_str(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, '<template-str>')
if errors:
return errors
return self.call_high(high)
|
Enforce the states in a template, pass the template as a string
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L3083-L3097
|
[
"def compile_template_str(template, renderers, default, blacklist, whitelist):\n '''\n Take template as a string and return the high data structure\n derived from the template.\n '''\n fn_ = salt.utils.files.mkstemp()\n with salt.utils.files.fopen(fn_, 'wb') as ofile:\n ofile.write(SLS_ENCODER(template)[0])\n return compile_template(fn_, renderers, default, blacklist, whitelist)\n",
"def call_high(self, high, orchestration_jid=None):\n '''\n Process a high data call and ensure the defined states.\n '''\n self.inject_default_call(high)\n errors = []\n # If there is extension data reconcile it\n high, ext_errors = self.reconcile_extend(high)\n errors.extend(ext_errors)\n errors.extend(self.verify_high(high))\n if errors:\n return errors\n high, req_in_errors = self.requisite_in(high)\n errors.extend(req_in_errors)\n high = self.apply_exclude(high)\n # Verify that the high data is structurally sound\n if errors:\n return errors\n # Compile and verify the raw chunks\n chunks = self.compile_high_data(high, orchestration_jid)\n\n # If there are extensions in the highstate, process them and update\n # the low data chunks\n if errors:\n return errors\n ret = self.call_chunks(chunks)\n ret = self.call_listen(chunks, ret)\n\n def _cleanup_accumulator_data():\n accum_data_path = os.path.join(\n get_accumulator_dir(self.opts['cachedir']),\n self.instance_id\n )\n try:\n os.remove(accum_data_path)\n log.debug('Deleted accumulator data file %s', accum_data_path)\n except OSError:\n log.debug('File %s does not exist, no need to cleanup', accum_data_path)\n _cleanup_accumulator_data()\n if self.jid is not None:\n pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)\n if os.path.isfile(pause_path):\n try:\n os.remove(pause_path)\n except OSError:\n # File is not present, all is well\n pass\n\n return ret\n",
"def render_template(self, high, template):\n errors = []\n if not high:\n return high, errors\n\n if not isinstance(high, dict):\n errors.append(\n 'Template {0} does not render to a dictionary'.format(template)\n )\n return high, errors\n\n invalid_items = ('include', 'exclude', 'extends')\n for item in invalid_items:\n if item in high:\n errors.append(\n 'The \\'{0}\\' declaration found on \\'{1}\\' is invalid when '\n 'rendering single templates'.format(item, template)\n )\n return high, errors\n\n for name in high:\n if not isinstance(high[name], dict):\n if isinstance(high[name], six.string_types):\n # Is this is a short state, it needs to be padded\n if '.' in high[name]:\n comps = high[name].split('.')\n high[name] = {\n # '__sls__': template,\n # '__env__': None,\n comps[0]: [comps[1]]\n }\n continue\n\n errors.append(\n 'ID {0} in template {1} is not a dictionary'.format(\n name, template\n )\n )\n continue\n skeys = set()\n for key in sorted(high[name]):\n if key.startswith('_'):\n continue\n if high[name][key] is None:\n errors.append(\n 'ID \\'{0}\\' in template {1} contains a short '\n 'declaration ({2}) with a trailing colon. When not '\n 'passing any arguments to a state, the colon must be '\n 'omitted.'.format(name, template, key)\n )\n continue\n if not isinstance(high[name][key], list):\n continue\n if '.' in key:\n comps = key.split('.')\n # Salt doesn't support state files such as:\n #\n # /etc/redis/redis.conf:\n # file.managed:\n # - user: redis\n # - group: redis\n # - mode: 644\n # file.comment:\n # - regex: ^requirepass\n if comps[0] in skeys:\n errors.append(\n 'ID \\'{0}\\' in template \\'{1}\\' contains multiple '\n 'state declarations of the same type'\n .format(name, template)\n )\n continue\n high[name][comps[0]] = high[name].pop(key)\n high[name][comps[0]].append(comps[1])\n skeys.add(comps[0])\n continue\n skeys.add(key)\n\n return high, errors\n"
] |
class State(object):
'''
Class used to execute salt states
'''
def __init__(
self,
opts,
pillar_override=None,
jid=None,
pillar_enc=None,
proxy=None,
context=None,
mocked=False,
loader='states',
initial_pillar=None):
self.states_loader = loader
if 'grains' not in opts:
opts['grains'] = salt.loader.grains(opts)
self.opts = opts
self.proxy = proxy
self._pillar_override = pillar_override
if pillar_enc is not None:
try:
pillar_enc = pillar_enc.lower()
except AttributeError:
pillar_enc = six.text_type(pillar_enc).lower()
self._pillar_enc = pillar_enc
log.debug('Gathering pillar data for state run')
if initial_pillar and not self._pillar_override:
self.opts['pillar'] = initial_pillar
else:
# Compile pillar data
self.opts['pillar'] = self._gather_pillar()
# Reapply overrides on top of compiled pillar
if self._pillar_override:
self.opts['pillar'] = salt.utils.dictupdate.merge(
self.opts['pillar'],
self._pillar_override,
self.opts.get('pillar_source_merging_strategy', 'smart'),
self.opts.get('renderer', 'yaml'),
self.opts.get('pillar_merge_lists', False))
log.debug('Finished gathering pillar data for state run')
self.state_con = context or {}
self.load_modules()
self.active = set()
self.mod_init = set()
self.pre = {}
self.__run_num = 0
self.jid = jid
self.instance_id = six.text_type(id(self))
self.inject_globals = {}
self.mocked = mocked
def _gather_pillar(self):
'''
Whenever a state run starts, gather the pillar data fresh
'''
if self._pillar_override:
if self._pillar_enc:
try:
self._pillar_override = salt.utils.crypt.decrypt(
self._pillar_override,
self._pillar_enc,
translate_newlines=True,
renderers=getattr(self, 'rend', None),
opts=self.opts,
valid_rend=self.opts['decrypt_pillar_renderers'])
except Exception as exc:
log.error('Failed to decrypt pillar override: %s', exc)
if isinstance(self._pillar_override, six.string_types):
# This can happen if an entire pillar dictionary was passed as
# a single encrypted string. The override will have been
# decrypted above, and should now be a stringified dictionary.
# Use the YAML loader to convert that to a Python dictionary.
try:
self._pillar_override = yamlloader.load(
self._pillar_override,
Loader=yamlloader.SaltYamlSafeLoader)
except Exception as exc:
log.error('Failed to load CLI pillar override')
log.exception(exc)
if not isinstance(self._pillar_override, dict):
log.error('Pillar override was not passed as a dictionary')
self._pillar_override = None
pillar = salt.pillar.get_pillar(
self.opts,
self.opts['grains'],
self.opts['id'],
self.opts['saltenv'],
pillar_override=self._pillar_override,
pillarenv=self.opts.get('pillarenv'))
return pillar.compile_pillar()
def _mod_init(self, low):
'''
Check the module initialization function, if this is the first run
of a state package that has a mod_init function, then execute the
mod_init function in the state module.
'''
# ensure that the module is loaded
try:
self.states['{0}.{1}'.format(low['state'], low['fun'])] # pylint: disable=W0106
except KeyError:
return
minit = '{0}.mod_init'.format(low['state'])
if low['state'] not in self.mod_init:
if minit in self.states._dict:
mret = self.states[minit](low)
if not mret:
return
self.mod_init.add(low['state'])
def _mod_aggregate(self, low, running, chunks):
'''
Execute the aggregation systems to runtime modify the low chunk
'''
agg_opt = self.functions['config.option']('state_aggregate')
if 'aggregate' in low:
agg_opt = low['aggregate']
if agg_opt is True:
agg_opt = [low['state']]
elif not isinstance(agg_opt, list):
return low
if low['state'] in agg_opt and not low.get('__agg__'):
agg_fun = '{0}.mod_aggregate'.format(low['state'])
if agg_fun in self.states:
try:
low = self.states[agg_fun](low, chunks, running)
low['__agg__'] = True
except TypeError:
log.error('Failed to execute aggregate for state %s', low['state'])
return low
def _run_check(self, low_data):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False, 'comment': []}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
if 'onlyif' in low_data:
_ret = self._run_check_onlyif(low_data, cmd_opts)
ret['result'] = _ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
ret['skip_watch'] = _ret['skip_watch']
if 'unless' in low_data:
_ret = self._run_check_unless(low_data, cmd_opts)
# If either result is True, the returned result should be True
ret['result'] = _ret['result'] or ret['result']
ret['comment'].append(_ret['comment'])
if 'skip_watch' in _ret:
# If either result is True, the returned result should be True
ret['skip_watch'] = _ret['skip_watch'] or ret['skip_watch']
return ret
def _run_check_onlyif(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['onlyif'], list):
low_data_onlyif = [low_data['onlyif']]
else:
low_data_onlyif = low_data['onlyif']
def _check_cmd(cmd):
if cmd != 0 and ret['result'] is False:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
elif cmd == 0:
ret.update({'comment': 'onlyif condition is true', 'result': False})
for entry in low_data_onlyif:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif not result:
ret.update({'comment': 'onlyif condition is false',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'onlyif condition is true',
'result': False})
else:
ret.update({'comment': 'onlyif execution failed, bad type passed', 'result': False})
return ret
def _run_check_unless(self, low_data, cmd_opts):
'''
Check that unless doesn't return 0, and that onlyif returns a 0.
'''
ret = {'result': False}
if not isinstance(low_data['unless'], list):
low_data_unless = [low_data['unless']]
else:
low_data_unless = low_data['unless']
def _check_cmd(cmd):
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
elif cmd != 0:
ret.update({'comment': 'unless condition is false', 'result': False})
for entry in low_data_unless:
if isinstance(entry, six.string_types):
cmd = self.functions['cmd.retcode'](entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
_check_cmd(cmd)
elif isinstance(entry, dict):
if 'fun' not in entry:
ret['comment'] = 'no `fun` argument in onlyif: {0}'.format(entry)
log.warning(ret['comment'])
return ret
result = self.functions[entry.pop('fun')](**entry)
if self.state_con.get('retcode', 0):
_check_cmd(self.state_con['retcode'])
elif result:
ret.update({'comment': 'unless condition is true',
'skip_watch': True,
'result': True})
else:
ret.update({'comment': 'unless condition is false',
'result': False})
else:
ret.update({'comment': 'unless condition is false, bad type passed', 'result': False})
# No reason to stop, return ret
return ret
def _run_check_cmd(self, low_data):
'''
Alter the way a successful state run is determined
'''
ret = {'result': False}
cmd_opts = {}
if 'shell' in self.opts['grains']:
cmd_opts['shell'] = self.opts['grains'].get('shell')
for entry in low_data['check_cmd']:
cmd = self.functions['cmd.retcode'](
entry, ignore_retcode=True, python_shell=True, **cmd_opts)
log.debug('Last command return code: %s', cmd)
if cmd == 0 and ret['result'] is False:
ret.update({'comment': 'check_cmd determined the state succeeded', 'result': True})
elif cmd != 0:
ret.update({'comment': 'check_cmd determined the state failed', 'result': False})
return ret
return ret
def reset_run_num(self):
'''
Rest the run_num value to 0
'''
self.__run_num = 0
def _load_states(self):
'''
Read the state loader value and loadup the correct states subsystem
'''
if self.states_loader == 'thorium':
self.states = salt.loader.thorium(self.opts, self.functions, {}) # TODO: Add runners, proxy?
else:
self.states = salt.loader.states(self.opts, self.functions, self.utils,
self.serializers, context=self.state_con, proxy=self.proxy)
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
self.utils = salt.loader.utils(self.opts)
self.functions = salt.loader.minion_mods(self.opts, self.state_con,
utils=self.utils,
proxy=self.proxy)
if isinstance(data, dict):
if data.get('provider', False):
if isinstance(data['provider'], six.string_types):
providers = [{data['state']: data['provider']}]
elif isinstance(data['provider'], list):
providers = data['provider']
else:
providers = {}
for provider in providers:
for mod in provider:
funcs = salt.loader.raw_mod(self.opts,
provider[mod],
self.functions)
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(
mod,
func[func.rindex('.'):]
)
self.functions[f_key] = funcs[func]
self.serializers = salt.loader.serializers(self.opts)
self._load_states()
self.rend = salt.loader.render(self.opts, self.functions,
states=self.states, proxy=self.proxy, context=self.state_con)
def module_refresh(self):
'''
Refresh all the modules
'''
log.debug('Refreshing modules...')
if self.opts['grains'].get('os') != 'MacOS':
# In case a package has been installed into the current python
# process 'site-packages', the 'site' module needs to be reloaded in
# order for the newly installed package to be importable.
try:
reload_module(site)
except RuntimeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
except TypeError:
log.error('Error encountered during module reload. Modules were not reloaded.')
self.load_modules()
if not self.opts.get('local', False) and self.opts.get('multiprocessing', True):
self.functions['saltutil.refresh_modules']()
def check_refresh(self, data, ret):
'''
Check to see if the modules for this state instance need to be updated,
only update if the state is a file or a package and if it changed
something. If the file function is managed check to see if the file is a
possible module type, e.g. a python, pyx, or .so. Always refresh if the
function is recurse, since that can lay down anything.
'''
_reload_modules = False
if data.get('reload_grains', False):
log.debug('Refreshing grains...')
self.opts['grains'] = salt.loader.grains(self.opts)
_reload_modules = True
if data.get('reload_pillar', False):
log.debug('Refreshing pillar...')
self.opts['pillar'] = self._gather_pillar()
_reload_modules = True
if not ret['changes']:
if data.get('force_reload_modules', False):
self.module_refresh()
return
if data.get('reload_modules', False) or _reload_modules:
# User explicitly requests a reload
self.module_refresh()
return
if data['state'] == 'file':
if data['fun'] == 'managed':
if data['name'].endswith(
('.py', '.pyx', '.pyo', '.pyc', '.so')):
self.module_refresh()
elif data['fun'] == 'recurse':
self.module_refresh()
elif data['fun'] == 'symlink':
if 'bin' in data['name']:
self.module_refresh()
elif data['state'] in ('pkg', 'ports'):
self.module_refresh()
def verify_data(self, data):
'''
Verify the data, return an error statement if something is wrong
'''
errors = []
if 'state' not in data:
errors.append('Missing "state" data')
if 'fun' not in data:
errors.append('Missing "fun" data')
if 'name' not in data:
errors.append('Missing "name" data')
if data['name'] and not isinstance(data['name'], six.string_types):
errors.append(
'ID \'{0}\' {1}is not formed as a string, but is a {2}'.format(
data['name'],
'in SLS \'{0}\' '.format(data['__sls__'])
if '__sls__' in data else '',
type(data['name']).__name__
)
)
if errors:
return errors
full = data['state'] + '.' + data['fun']
if full not in self.states:
if '__sls__' in data:
errors.append(
'State \'{0}\' was not found in SLS \'{1}\''.format(
full,
data['__sls__']
)
)
reason = self.states.missing_fun_string(full)
if reason:
errors.append('Reason: {0}'.format(reason))
else:
errors.append(
'Specified state \'{0}\' was not found'.format(
full
)
)
else:
# First verify that the parameters are met
aspec = salt.utils.args.get_function_argspec(self.states[full])
arglen = 0
deflen = 0
if isinstance(aspec.args, list):
arglen = len(aspec.args)
if isinstance(aspec.defaults, tuple):
deflen = len(aspec.defaults)
for ind in range(arglen - deflen):
if aspec.args[ind] not in data:
errors.append(
'Missing parameter {0} for state {1}'.format(
aspec.args[ind],
full
)
)
# If this chunk has a recursive require, then it will cause a
# recursive loop when executing, check for it
reqdec = ''
if 'require' in data:
reqdec = 'require'
if 'watch' in data:
# Check to see if the service has a mod_watch function, if it does
# not, then just require
# to just require extend the require statement with the contents
# of watch so that the mod_watch function is not called and the
# requisite capability is still used
if '{0}.mod_watch'.format(data['state']) not in self.states:
if 'require' in data:
data['require'].extend(data.pop('watch'))
else:
data['require'] = data.pop('watch')
reqdec = 'require'
else:
reqdec = 'watch'
if reqdec:
for req in data[reqdec]:
reqfirst = next(iter(req))
if data['state'] == reqfirst:
if (fnmatch.fnmatch(data['name'], req[reqfirst])
or fnmatch.fnmatch(data['__id__'], req[reqfirst])):
err = ('Recursive require detected in SLS {0} for'
' require {1} in ID {2}').format(
data['__sls__'],
req,
data['__id__'])
errors.append(err)
return errors
def verify_high(self, high):
'''
Verify that the high data is viable and follows the data structure
'''
errors = []
if not isinstance(high, dict):
errors.append('High data is not a dictionary and is invalid')
reqs = OrderedDict()
for name, body in six.iteritems(high):
try:
if name.startswith('__'):
continue
except AttributeError:
pass
if not isinstance(name, six.string_types):
errors.append(
'ID \'{0}\' in SLS \'{1}\' is not formed as a string, but '
'is a {2}. It may need to be quoted.'.format(
name, body['__sls__'], type(name).__name__)
)
if not isinstance(body, dict):
err = ('The type {0} in {1} is not formatted as a dictionary'
.format(name, body))
errors.append(err)
continue
for state in body:
if state.startswith('__'):
continue
if body[state] is None:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains a short declaration '
'({2}) with a trailing colon. When not passing any '
'arguments to a state, the colon must be omitted.'
.format(name, body['__sls__'], state)
)
continue
if not isinstance(body[state], list):
errors.append(
'State \'{0}\' in SLS \'{1}\' is not formed as a list'
.format(name, body['__sls__'])
)
else:
fun = 0
if '.' in state:
fun += 1
for arg in body[state]:
if isinstance(arg, six.string_types):
fun += 1
if ' ' in arg.strip():
errors.append(('The function "{0}" in state '
'"{1}" in SLS "{2}" has '
'whitespace, a function with whitespace is '
'not supported, perhaps this is an argument '
'that is missing a ":"').format(
arg,
name,
body['__sls__']))
elif isinstance(arg, dict):
# The arg is a dict, if the arg is require or
# watch, it must be a list.
#
# Add the requires to the reqs dict and check them
# all for recursive requisites.
argfirst = next(iter(arg))
if argfirst == 'names':
if not isinstance(arg[argfirst], list):
errors.append(
'The \'names\' argument in state '
'\'{0}\' in SLS \'{1}\' needs to be '
'formed as a list'
.format(name, body['__sls__'])
)
if argfirst in ('require', 'watch', 'prereq', 'onchanges'):
if not isinstance(arg[argfirst], list):
errors.append(
'The {0} statement in state \'{1}\' in '
'SLS \'{2}\' needs to be formed as a '
'list'.format(argfirst,
name,
body['__sls__'])
)
# It is a list, verify that the members of the
# list are all single key dicts.
else:
reqs[name] = OrderedDict(state=state)
for req in arg[argfirst]:
if isinstance(req, six.string_types):
req = {'id': req}
if not isinstance(req, dict):
err = ('Requisite declaration {0}'
' in SLS {1} is not formed as a'
' single key dictionary').format(
req,
body['__sls__'])
errors.append(err)
continue
req_key = next(iter(req))
req_val = req[req_key]
if '.' in req_key:
errors.append(
'Invalid requisite type \'{0}\' '
'in state \'{1}\', in SLS '
'\'{2}\'. Requisite types must '
'not contain dots, did you '
'mean \'{3}\'?'.format(
req_key,
name,
body['__sls__'],
req_key[:req_key.find('.')]
)
)
if not ishashable(req_val):
errors.append((
'Illegal requisite "{0}", '
'please check your syntax.\n'
).format(req_val))
continue
# Check for global recursive requisites
reqs[name][req_val] = req_key
# I am going beyond 80 chars on
# purpose, this is just too much
# of a pain to deal with otherwise
if req_val in reqs:
if name in reqs[req_val]:
if reqs[req_val][name] == state:
if reqs[req_val]['state'] == reqs[name][req_val]:
err = ('A recursive '
'requisite was found, SLS '
'"{0}" ID "{1}" ID "{2}"'
).format(
body['__sls__'],
name,
req_val
)
errors.append(err)
# Make sure that there is only one key in the
# dict
if len(list(arg)) != 1:
errors.append(
'Multiple dictionaries defined in '
'argument of state \'{0}\' in SLS \'{1}\''
.format(name, body['__sls__'])
)
if not fun:
if state == 'require' or state == 'watch':
continue
errors.append(
'No function declared in state \'{0}\' in SLS \'{1}\''
.format(state, body['__sls__'])
)
elif fun > 1:
errors.append(
'Too many functions declared in state \'{0}\' in '
'SLS \'{1}\''.format(state, body['__sls__'])
)
return errors
def verify_chunks(self, chunks):
'''
Verify the chunks in a list of low data structures
'''
err = []
for chunk in chunks:
err.extend(self.verify_data(chunk))
return err
def order_chunks(self, chunks):
'''
Sort the chunk list verifying that the chunks follow the order
specified in the order options.
'''
cap = 1
for chunk in chunks:
if 'order' in chunk:
if not isinstance(chunk['order'], int):
continue
chunk_order = chunk['order']
if chunk_order > cap - 1 and chunk_order > 0:
cap = chunk_order + 100
for chunk in chunks:
if 'order' not in chunk:
chunk['order'] = cap
continue
if not isinstance(chunk['order'], (int, float)):
if chunk['order'] == 'last':
chunk['order'] = cap + 1000000
elif chunk['order'] == 'first':
chunk['order'] = 0
else:
chunk['order'] = cap
if 'name_order' in chunk:
chunk['order'] = chunk['order'] + chunk.pop('name_order') / 10000.0
if chunk['order'] < 0:
chunk['order'] = cap + 1000000 + chunk['order']
chunks.sort(key=lambda chunk: (chunk['order'], '{0[state]}{0[name]}{0[fun]}'.format(chunk)))
return chunks
def compile_high_data(self, high, orchestration_jid=None):
'''
"Compile" the high data as it is retrieved from the CLI or YAML into
the individual state executor structures
'''
chunks = []
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
for state, run in six.iteritems(body):
funcs = set()
names = []
if state.startswith('__'):
continue
chunk = OrderedDict()
chunk['state'] = state
chunk['name'] = name
if orchestration_jid is not None:
chunk['__orchestration_jid__'] = orchestration_jid
if '__sls__' in body:
chunk['__sls__'] = body['__sls__']
if '__env__' in body:
chunk['__env__'] = body['__env__']
chunk['__id__'] = name
for arg in run:
if isinstance(arg, six.string_types):
funcs.add(arg)
continue
if isinstance(arg, dict):
for key, val in six.iteritems(arg):
if key == 'names':
for _name in val:
if _name not in names:
names.append(_name)
elif key == 'state':
# Don't pass down a state override
continue
elif (key == 'name' and
not isinstance(val, six.string_types)):
# Invalid name, fall back to ID
chunk[key] = name
else:
chunk[key] = val
if names:
name_order = 1
for entry in names:
live = copy.deepcopy(chunk)
if isinstance(entry, dict):
low_name = next(six.iterkeys(entry))
live['name'] = low_name
list(map(live.update, entry[low_name]))
else:
live['name'] = entry
live['name_order'] = name_order
name_order += 1
for fun in funcs:
live['fun'] = fun
chunks.append(live)
else:
live = copy.deepcopy(chunk)
for fun in funcs:
live['fun'] = fun
chunks.append(live)
chunks = self.order_chunks(chunks)
return chunks
def reconcile_extend(self, high):
'''
Pull the extend data and add it to the respective high data
'''
errors = []
if '__extend__' not in high:
return high, errors
ext = high.pop('__extend__')
for ext_chunk in ext:
for name, body in six.iteritems(ext_chunk):
if name not in high:
state_type = next(
x for x in body if not x.startswith('__')
)
# Check for a matching 'name' override in high data
ids = find_name(name, state_type, high)
if len(ids) != 1:
errors.append(
'Cannot extend ID \'{0}\' in \'{1}:{2}\'. It is not '
'part of the high state.\n'
'This is likely due to a missing include statement '
'or an incorrectly typed ID.\nEnsure that a '
'state with an ID of \'{0}\' is available\nin '
'environment \'{1}\' and to SLS \'{2}\''.format(
name,
body.get('__env__', 'base'),
body.get('__sls__', 'base'))
)
continue
else:
name = ids[0][0]
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
if state not in high[name]:
high[name][state] = run
continue
# high[name][state] is extended by run, both are lists
for arg in run:
update = False
for hind in range(len(high[name][state])):
if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):
# replacing the function, replace the index
high[name][state].pop(hind)
high[name][state].insert(hind, arg)
update = True
continue
if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):
# It is an option, make sure the options match
argfirst = next(iter(arg))
if argfirst == next(iter(high[name][state][hind])):
# If argfirst is a requisite then we must merge
# our requisite with that of the target state
if argfirst in STATE_REQUISITE_KEYWORDS:
high[name][state][hind][argfirst].extend(arg[argfirst])
# otherwise, its not a requisite and we are just extending (replacing)
else:
high[name][state][hind] = arg
update = True
if (argfirst == 'name' and
next(iter(high[name][state][hind])) == 'names'):
# If names are overwritten by name use the name
high[name][state][hind] = arg
if not update:
high[name][state].append(arg)
return high, errors
def apply_exclude(self, high):
'''
Read in the __exclude__ list and remove all excluded objects from the
high data
'''
if '__exclude__' not in high:
return high
ex_sls = set()
ex_id = set()
exclude = high.pop('__exclude__')
for exc in exclude:
if isinstance(exc, six.string_types):
# The exclude statement is a string, assume it is an sls
ex_sls.add(exc)
if isinstance(exc, dict):
# Explicitly declared exclude
if len(exc) != 1:
continue
key = next(six.iterkeys(exc))
if key == 'sls':
ex_sls.add(exc['sls'])
elif key == 'id':
ex_id.add(exc['id'])
# Now the excludes have been simplified, use them
if ex_sls:
# There are sls excludes, find the associated ids
for name, body in six.iteritems(high):
if name.startswith('__'):
continue
sls = body.get('__sls__', '')
if not sls:
continue
for ex_ in ex_sls:
if fnmatch.fnmatch(sls, ex_):
ex_id.add(name)
for id_ in ex_id:
if id_ in high:
high.pop(id_)
return high
def requisite_in(self, high):
'''
Extend the data reference with requisite_in arguments
'''
req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}
req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})
extend = {}
errors = []
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
for id_, body in six.iteritems(high):
if not isinstance(body, dict):
continue
for state, run in six.iteritems(body):
if state.startswith('__'):
continue
for arg in run:
if isinstance(arg, dict):
# It is not a function, verify that the arg is a
# requisite in statement
if not arg:
# Empty arg dict
# How did we get this far?
continue
# Split out the components
key = next(iter(arg))
if key not in req_in:
continue
if key in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', key)
continue
rkey = key.split('_')[0]
items = arg[key]
if isinstance(items, dict):
# Formatted as a single req_in
for _state, name in six.iteritems(items):
# Not a use requisite_in
found = False
if name not in extend:
extend[name] = OrderedDict()
if '.' in _state:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
_state,
name,
body['__sls__'],
_state[:_state.find('.')]
)
)
_state = _state.split('.')[0]
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
if isinstance(items, list):
# Formed as a list of requisite additions
hinges = []
for ind in items:
if not isinstance(ind, dict):
# Malformed req_in
if ind in high:
_ind_high = [x for x
in high[ind]
if not x.startswith('__')]
ind = {_ind_high[0]: ind}
else:
found = False
for _id in iter(high):
for state in [state for state
in iter(high[_id])
if not state.startswith('__')]:
for j in iter(high[_id][state]):
if isinstance(j, dict) and 'name' in j:
if j['name'] == ind:
ind = {state: _id}
found = True
if not found:
continue
if not ind:
continue
pstate = next(iter(ind))
pname = ind[pstate]
if pstate == 'sls':
# Expand hinges here
hinges = find_sls_ids(pname, high)
else:
hinges.append((pname, pstate))
if '.' in pstate:
errors.append(
'Invalid requisite in {0}: {1} for '
'{2}, in SLS \'{3}\'. Requisites must '
'not contain dots, did you mean \'{4}\'?'
.format(
rkey,
pstate,
pname,
body['__sls__'],
pstate[:pstate.find('.')]
)
)
pstate = pstate.split(".")[0]
for tup in hinges:
name, _state = tup
if key == 'prereq_in':
# Add prerequired to origin
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
extend[id_][state].append(
{'prerequired': [{_state: name}]}
)
if key == 'prereq':
# Add prerequired to prereqs
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
extend[ext_id][_req_state].append(
{'prerequired': [{state: id_}]}
)
continue
if key == 'use_in':
# Add the running states args to the
# use_in states
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
ext_args = state_args(ext_id, _state, high)
if ext_id not in extend:
extend[ext_id] = OrderedDict()
if _req_state not in extend[ext_id]:
extend[ext_id][_req_state] = []
ignore_args = req_in_all.union(ext_args)
for arg in high[id_][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[ext_id][_req_state].append(arg)
continue
if key == 'use':
# Add the use state's args to the
# running state
ext_ids = find_name(name, _state, high)
for ext_id, _req_state in ext_ids:
if not ext_id:
continue
loc_args = state_args(id_, state, high)
if id_ not in extend:
extend[id_] = OrderedDict()
if state not in extend[id_]:
extend[id_][state] = []
ignore_args = req_in_all.union(loc_args)
for arg in high[ext_id][_req_state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if next(iter(arg)) in ignore_args:
continue
# Don't use name or names
if next(six.iterkeys(arg)) == 'name':
continue
if next(six.iterkeys(arg)) == 'names':
continue
extend[id_][state].append(arg)
continue
found = False
if name not in extend:
extend[name] = OrderedDict()
if _state not in extend[name]:
extend[name][_state] = []
extend[name]['__env__'] = body['__env__']
extend[name]['__sls__'] = body['__sls__']
for ind in range(len(extend[name][_state])):
if next(iter(
extend[name][_state][ind])) == rkey:
# Extending again
extend[name][_state][ind][rkey].append(
{state: id_}
)
found = True
if found:
continue
# The rkey is not present yet, create it
extend[name][_state].append(
{rkey: [{state: id_}]}
)
high['__extend__'] = []
for key, val in six.iteritems(extend):
high['__extend__'].append({key: val})
req_in_high, req_in_errors = self.reconcile_extend(high)
errors.extend(req_in_errors)
return req_in_high, errors
def _call_parallel_target(self, name, cdata, low):
'''
The target function to call that will create the parallel thread/process
'''
# we need to re-record start/end duration here because it is impossible to
# correctly calculate further down the chain
utc_start_time = datetime.datetime.utcnow()
tag = _gen_tag(low)
try:
ret = self.states[cdata['full']](*cdata['args'],
**cdata['kwargs'])
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
utc_finish_time = datetime.datetime.utcnow()
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
troot = os.path.join(self.opts['cachedir'], self.jid)
tfile = os.path.join(
troot,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isdir(troot):
try:
os.makedirs(troot)
except OSError:
# Looks like the directory was created between the check
# and the attempt, we are safe to pass
pass
with salt.utils.files.fopen(tfile, 'wb+') as fp_:
fp_.write(msgpack_serialize(ret))
def call_parallel(self, cdata, low):
'''
Call the state defined in the given cdata in parallel
'''
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
proc = salt.utils.process.MultiprocessingProcess(
target=self._call_parallel_target,
args=(name, cdata, low))
proc.start()
ret = {'name': name,
'result': None,
'changes': {},
'comment': 'Started in a separate process',
'proc': proc}
return ret
@salt.utils.decorators.state.OutputUnifier('content_check', 'unify')
def call(self, low, chunks=None, running=None, retries=1):
'''
Call a state directly with the low data structure, verify data
before processing.
'''
use_uptime = False
if os.path.isfile('/proc/uptime'):
use_uptime = True
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
start_uptime = float(fp_.readline().split()[0])
utc_start_time = datetime.datetime.utcnow()
local_start_time = utc_start_time - (datetime.datetime.utcnow() - datetime.datetime.now())
log.info('Running state [%s] at time %s',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_start_time.time().isoformat()
)
errors = self.verify_data(low)
if errors:
ret = {
'result': False,
'name': low['name'],
'changes': {},
'comment': '',
}
for err in errors:
ret['comment'] += '{0}\n'.format(err)
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
return ret
else:
ret = {'result': False, 'name': low['name'], 'changes': {}}
self.state_con['runas'] = low.get('runas', None)
if low['state'] == 'cmd' and 'password' in low:
self.state_con['runas_password'] = low['password']
else:
self.state_con['runas_password'] = low.get('runas_password', None)
if not low.get('__prereq__'):
log.info(
'Executing state %s.%s for [%s]',
low['state'],
low['fun'],
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name']
)
if 'provider' in low:
self.load_modules(low)
state_func_name = '{0[state]}.{0[fun]}'.format(low)
cdata = salt.utils.args.format_call(
self.states[state_func_name],
low,
initial_ret={'full': state_func_name},
expected_extra_kws=STATE_INTERNAL_KEYWORDS
)
inject_globals = {
# Pass a copy of the running dictionary, the low state chunks and
# the current state dictionaries.
# We pass deep copies here because we don't want any misbehaving
# state module to change these at runtime.
'__low__': immutabletypes.freeze(low),
'__running__': immutabletypes.freeze(running) if running else {},
'__instance_id__': self.instance_id,
'__lowstate__': immutabletypes.freeze(chunks) if chunks else {}
}
if '__env__' in low:
inject_globals['__env__'] = six.text_type(low['__env__'])
if self.inject_globals:
inject_globals.update(self.inject_globals)
if low.get('__prereq__'):
test = sys.modules[self.states[cdata['full']].__module__].__opts__['test']
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = True
try:
# Let's get a reference to the salt environment to use within this
# state call.
#
# If the state function accepts an 'env' keyword argument, it
# allows the state to be overridden(we look for that in cdata). If
# that's not found in cdata, we look for what we're being passed in
# the original data, namely, the special dunder __env__. If that's
# not found we default to 'base'
if ('unless' in low and '{0[state]}.mod_run_check'.format(low) not in self.states) or \
('onlyif' in low and '{0[state]}.mod_run_check'.format(low) not in self.states):
ret.update(self._run_check(low))
if not self.opts.get('lock_saltenv', False):
# NOTE: Overriding the saltenv when lock_saltenv is blocked in
# salt/modules/state.py, before we ever get here, but this
# additional check keeps use of the State class outside of the
# salt/modules/state.py from getting around this setting.
if 'saltenv' in low:
inject_globals['__env__'] = six.text_type(low['saltenv'])
elif isinstance(cdata['kwargs'].get('env', None), six.string_types):
# User is using a deprecated env setting which was parsed by
# format_call.
# We check for a string type since module functions which
# allow setting the OS environ also make use of the "env"
# keyword argument, which is not a string
inject_globals['__env__'] = six.text_type(cdata['kwargs']['env'])
if '__env__' not in inject_globals:
# Let's use the default environment
inject_globals['__env__'] = 'base'
if '__orchestration_jid__' in low:
inject_globals['__orchestration_jid__'] = \
low['__orchestration_jid__']
if 'result' not in ret or ret['result'] is False:
self.states.inject_globals = inject_globals
if self.mocked:
ret = mock_ret(cdata)
else:
# Execute the state function
if not low.get('__prereq__') and low.get('parallel'):
# run the state call in parallel, but only if not in a prereq
ret = self.call_parallel(cdata, low)
else:
self.format_slots(cdata)
if cdata['full'].split('.')[-1] == '__call__':
# __call__ requires OrderedDict to preserve state order
# kwargs are also invalid overall
ret = self.states[cdata['full']](cdata['args'], module=None, state=cdata['kwargs'])
else:
ret = self.states[cdata['full']](*cdata['args'], **cdata['kwargs'])
self.states.inject_globals = {}
if 'check_cmd' in low and '{0[state]}.mod_run_check_cmd'.format(low) not in self.states:
ret.update(self._run_check_cmd(low))
except Exception as exc:
log.debug('An exception occurred in this state: %s', exc,
exc_info_on_loglevel=logging.DEBUG)
trb = traceback.format_exc()
# There are a number of possibilities to not have the cdata
# populated with what we might have expected, so just be smart
# enough to not raise another KeyError as the name is easily
# guessable and fallback in all cases to present the real
# exception to the user
name = (cdata.get('args') or [None])[0] or cdata['kwargs'].get('name')
if not name:
name = low.get('name', low.get('__id__'))
ret = {
'result': False,
'name': name,
'changes': {},
'comment': 'An exception occurred in this state: {0}'.format(trb)
}
finally:
if low.get('__prereq__'):
sys.modules[self.states[cdata['full']].__module__].__opts__['test'] = test
self.state_con.pop('runas', None)
self.state_con.pop('runas_password', None)
if not isinstance(ret, dict):
return ret
# If format_call got any warnings, let's show them to the user
if 'warnings' in cdata:
ret.setdefault('warnings', []).extend(cdata['warnings'])
if 'provider' in low:
self.load_modules()
if low.get('__prereq__'):
low['__prereq__'] = False
return ret
ret['__sls__'] = low.get('__sls__')
ret['__run_num__'] = self.__run_num
self.__run_num += 1
format_log(ret)
self.check_refresh(low, ret)
if use_uptime:
with salt.utils.files.fopen('/proc/uptime', 'r') as fp_:
finish_uptime = float(fp_.readline().split()[0])
utc_finish_time = datetime.datetime.utcnow()
timezone_delta = datetime.datetime.utcnow() - datetime.datetime.now()
local_finish_time = utc_finish_time - timezone_delta
local_start_time = utc_start_time - timezone_delta
ret['start_time'] = local_start_time.time().isoformat()
if use_uptime:
duration = (finish_uptime - start_uptime) * 1000.0
else:
delta = (utc_finish_time - utc_start_time)
# duration in milliseconds.microseconds
duration = (delta.seconds * 1000000 + delta.microseconds) / 1000.0
ret['duration'] = duration
ret['__id__'] = low['__id__']
log.info(
'Completed state [%s] at time %s (duration_in_ms=%s)',
low['name'].strip() if isinstance(low['name'], six.string_types)
else low['name'],
local_finish_time.time().isoformat(),
duration
)
if 'retry' in low:
low['retry'] = self.verify_retry_data(low['retry'])
if not sys.modules[self.states[cdata['full']].__module__].__opts__['test']:
if low['retry']['until'] != ret['result']:
if low['retry']['attempts'] > retries:
interval = low['retry']['interval']
if low['retry']['splay'] != 0:
interval = interval + random.randint(0, low['retry']['splay'])
log.info(
'State result does not match retry until value, '
'state will be re-run in %s seconds', interval
)
self.functions['test.sleep'](interval)
retry_ret = self.call(low, chunks, running, retries=retries+1)
orig_ret = ret
ret = retry_ret
ret['comment'] = '\n'.join(
[(
'Attempt {0}: Returned a result of "{1}", '
'with the following comment: "{2}"'.format(
retries,
orig_ret['result'],
orig_ret['comment'])
),
'' if not ret['comment'] else ret['comment']])
ret['duration'] = ret['duration'] + orig_ret['duration'] + (interval * 1000)
if retries == 1:
ret['start_time'] = orig_ret['start_time']
else:
ret['comment'] = ' '.join(
['' if not ret['comment'] else ret['comment'],
('The state would be retried every {1} seconds '
'(with a splay of up to {3} seconds) '
'a maximum of {0} times or until a result of {2} '
'is returned').format(low['retry']['attempts'],
low['retry']['interval'],
low['retry']['until'],
low['retry']['splay'])])
return ret
def __eval_slot(self, slot):
log.debug('Evaluating slot: %s', slot)
fmt = slot.split(':', 2)
if len(fmt) != 3:
log.warning('Malformed slot: %s', slot)
return slot
if fmt[1] != 'salt':
log.warning('Malformed slot: %s', slot)
log.warning('Only execution modules are currently supported in slots. This means slot '
'should start with "__slot__:salt:"')
return slot
fun, args, kwargs = salt.utils.args.parse_function(fmt[2])
if not fun or fun not in self.functions:
log.warning('Malformed slot: %s', slot)
log.warning('Execution module should be specified in a function call format: '
'test.arg(\'arg\', kw=\'kwarg\')')
return slot
log.debug('Calling slot: %s(%s, %s)', fun, args, kwargs)
slot_return = self.functions[fun](*args, **kwargs)
# Given input __slot__:salt:test.arg(somekey="value").not.exist ~ /appended
# slot_text should be __slot...).not.exist
# append_data should be ~ /appended
slot_text = fmt[2].split('~')[0]
append_data = fmt[2].split('~', 1)[1:]
log.debug('slot_text: %s', slot_text)
log.debug('append_data: %s', append_data)
# Support parsing slot dict response
# return_get should result in a kwargs.nested.dict path by getting
# everything after first closing paren: )
return_get = None
try:
return_get = slot_text[slot_text.rindex(')')+1:]
except ValueError:
pass
if return_get:
#remove first period
return_get = return_get.split('.', 1)[1].strip()
log.debug('Searching slot result %s for %s', slot_return, return_get)
slot_return = salt.utils.data.traverse_dict_and_list(slot_return,
return_get,
default=None,
delimiter='.'
)
if append_data:
if isinstance(slot_return, six.string_types):
# Append text to slot string result
append_data = ' '.join(append_data).strip()
log.debug('appending to slot result: %s', append_data)
slot_return += append_data
else:
log.error('Ignoring slot append, slot result is not a string')
return slot_return
def format_slots(self, cdata):
'''
Read in the arguments from the low level slot syntax to make a last
minute runtime call to gather relevant data for the specific routine
Will parse strings, first level of dictionary values, and strings and
first level dict values inside of lists
'''
# __slot__:salt.cmd.run(foo, bar, baz=qux)
SLOT_TEXT = '__slot__:'
ctx = (('args', enumerate(cdata['args'])),
('kwargs', cdata['kwargs'].items()))
for atype, avalues in ctx:
for ind, arg in avalues:
arg = salt.utils.data.decode(arg, keep=True)
if isinstance(arg, dict):
# Search dictionary values for __slot__:
for key, value in arg.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing dict value %s", value)
cdata[atype][ind][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
elif isinstance(arg, list):
for idx, listvalue in enumerate(arg):
log.trace("Slot processing list value: %s", listvalue)
if isinstance(listvalue, dict):
# Search dict values in list for __slot__:
for key, value in listvalue.items():
try:
if value.startswith(SLOT_TEXT):
log.trace("Slot processsing nested dict value %s", value)
cdata[atype][ind][idx][key] = self.__eval_slot(value)
except AttributeError:
# Not a string/slot
continue
if isinstance(listvalue, six.text_type):
# Search strings in a list for __slot__:
if listvalue.startswith(SLOT_TEXT):
log.trace("Slot processsing nested string %s", listvalue)
cdata[atype][ind][idx] = self.__eval_slot(listvalue)
elif isinstance(arg, six.text_type) \
and arg.startswith(SLOT_TEXT):
# Search strings for __slot__:
log.trace("Slot processsing %s", arg)
cdata[atype][ind] = self.__eval_slot(arg)
else:
# Not a slot, skip it
continue
def verify_retry_data(self, retry_data):
'''
verifies the specified retry data
'''
retry_defaults = {
'until': True,
'attempts': 2,
'splay': 0,
'interval': 30,
}
expected_data = {
'until': bool,
'attempts': int,
'interval': int,
'splay': int,
}
validated_retry_data = {}
if isinstance(retry_data, dict):
for expected_key, value_type in six.iteritems(expected_data):
if expected_key in retry_data:
if isinstance(retry_data[expected_key], value_type):
validated_retry_data[expected_key] = retry_data[expected_key]
else:
log.warning(
'An invalid value was passed for the retry %s, '
'using default value \'%s\'',
expected_key, retry_defaults[expected_key]
)
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
validated_retry_data[expected_key] = retry_defaults[expected_key]
else:
log.warning(('State is set to retry, but a valid dict for retry '
'configuration was not found. Using retry defaults'))
validated_retry_data = retry_defaults
return validated_retry_data
def call_chunks(self, chunks):
'''
Iterate over a list of chunks and call them, checking for requires.
'''
# Check for any disabled states
disabled = {}
if 'state_runs_disabled' in self.opts['grains']:
for low in chunks[:]:
state_ = '{0}.{1}'.format(low['state'], low['fun'])
for pat in self.opts['grains']['state_runs_disabled']:
if fnmatch.fnmatch(state_, pat):
comment = (
'The state function "{0}" is currently disabled by "{1}", '
'to re-enable, run state.enable {1}.'
).format(
state_,
pat,
)
_tag = _gen_tag(low)
disabled[_tag] = {'changes': {},
'result': False,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
chunks.remove(low)
break
running = {}
for low in chunks:
if '__FAILHARD__' in running:
running.pop('__FAILHARD__')
return running
tag = _gen_tag(low)
if tag not in running:
# Check if this low chunk is paused
action = self.check_pause(low)
if action == 'kill':
break
running = self.call_chunk(low, running, chunks)
if self.check_failhard(low, running):
return running
self.active = set()
while True:
if self.reconcile_procs(running):
break
time.sleep(0.01)
ret = dict(list(disabled.items()) + list(running.items()))
return ret
def check_failhard(self, low, running):
'''
Check if the low data chunk should send a failhard signal
'''
tag = _gen_tag(low)
if self.opts.get('test', False):
return False
if low.get('failhard', self.opts['failhard']) and tag in running:
if running[tag]['result'] is None:
return False
return not running[tag]['result']
return False
def check_pause(self, low):
'''
Check to see if this low chunk has been paused
'''
if not self.jid:
# Can't pause on salt-ssh since we can't track continuous state
return
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
start = time.time()
if os.path.isfile(pause_path):
try:
while True:
tries = 0
with salt.utils.files.fopen(pause_path, 'rb') as fp_:
try:
pdat = msgpack_deserialize(fp_.read())
except msgpack.UnpackValueError:
# Reading race condition
if tries > 10:
# Break out if there are a ton of read errors
return
tries += 1
time.sleep(1)
continue
id_ = low['__id__']
key = ''
if id_ in pdat:
key = id_
elif '__all__' in pdat:
key = '__all__'
if key:
if 'duration' in pdat[key]:
now = time.time()
if now - start > pdat[key]['duration']:
return 'run'
if 'kill' in pdat[key]:
return 'kill'
else:
return 'run'
time.sleep(1)
except Exception as exc:
log.error('Failed to read in pause data for file located at: %s', pause_path)
return 'run'
return 'run'
def reconcile_procs(self, running):
'''
Check the running dict for processes and resolve them
'''
retset = set()
for tag in running:
proc = running[tag].get('proc')
if proc:
if not proc.is_alive():
ret_cache = os.path.join(
self.opts['cachedir'],
self.jid,
salt.utils.hashutils.sha1_digest(tag))
if not os.path.isfile(ret_cache):
ret = {'result': False,
'comment': 'Parallel process failed to return',
'name': running[tag]['name'],
'changes': {}}
try:
with salt.utils.files.fopen(ret_cache, 'rb') as fp_:
ret = msgpack_deserialize(fp_.read())
except (OSError, IOError):
ret = {'result': False,
'comment': 'Parallel cache failure',
'name': running[tag]['name'],
'changes': {}}
running[tag].update(ret)
running[tag].pop('proc')
else:
retset.add(False)
return False not in retset
def check_requisite(self, low, running, chunks, pre=False):
'''
Look into the running data to check the status of all requisite
states
'''
disabled_reqs = self.opts.get('disabled_requisites', [])
if not isinstance(disabled_reqs, list):
disabled_reqs = [disabled_reqs]
present = False
# If mod_watch is not available make it a require
if 'watch' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require' in low:
low['require'].extend(low.pop('watch'))
else:
low['require'] = low.pop('watch')
else:
present = True
if 'watch_any' in low:
if '{0}.mod_watch'.format(low['state']) not in self.states:
if 'require_any' in low:
low['require_any'].extend(low.pop('watch_any'))
else:
low['require_any'] = low.pop('watch_any')
else:
present = True
if 'require' in low:
present = True
if 'require_any' in low:
present = True
if 'prerequired' in low:
present = True
if 'prereq' in low:
present = True
if 'onfail' in low:
present = True
if 'onfail_any' in low:
present = True
if 'onfail_all' in low:
present = True
if 'onchanges' in low:
present = True
if 'onchanges_any' in low:
present = True
if not present:
return 'met', ()
self.reconcile_procs(running)
reqs = {
'require': [],
'require_any': [],
'watch': [],
'watch_any': [],
'prereq': [],
'onfail': [],
'onfail_any': [],
'onfail_all': [],
'onchanges': [],
'onchanges_any': []}
if pre:
reqs['prerequired'] = []
for r_state in reqs:
if r_state in low and low[r_state] is not None:
if r_state in disabled_reqs:
log.warning('The %s requisite has been disabled, Ignoring.', r_state)
continue
for req in low[r_state]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
for chunk in chunks:
req_key = next(iter(req))
req_val = req[req_key]
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
found = True
reqs[r_state].append(chunk)
continue
try:
if isinstance(req_val, six.string_types):
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
found = True
reqs[r_state].append(chunk)
else:
raise KeyError
except KeyError as exc:
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
except TypeError:
# On Python 2, the above req_val, being an OrderedDict, will raise a KeyError,
# however on Python 3 it will raise a TypeError
# This was found when running tests.unit.test_state.StateCompilerTestCase.test_render_error_on_invalid_requisite
raise SaltRenderError(
'Could not locate requisite of [{0}] present in state with name [{1}]'.format(
req_key, chunk['name']))
if not found:
return 'unmet', ()
fun_stats = set()
for r_state, chunks in six.iteritems(reqs):
req_stats = set()
if r_state.startswith('prereq') and not r_state.startswith('prerequired'):
run_dict = self.pre
else:
run_dict = running
while True:
if self.reconcile_procs(run_dict):
break
time.sleep(0.01)
for chunk in chunks:
tag = _gen_tag(chunk)
if tag not in run_dict:
req_stats.add('unmet')
continue
if r_state.startswith('onfail'):
if run_dict[tag]['result'] is True:
req_stats.add('onfail') # At least one state is OK
continue
else:
if run_dict[tag]['result'] is False:
req_stats.add('fail')
continue
if r_state.startswith('onchanges'):
if not run_dict[tag]['changes']:
req_stats.add('onchanges')
else:
req_stats.add('onchangesmet')
continue
if r_state.startswith('watch') and run_dict[tag]['changes']:
req_stats.add('change')
continue
if r_state.startswith('prereq') and run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('premet')
if r_state.startswith('prereq') and not run_dict[tag]['result'] is None:
if not r_state.startswith('prerequired'):
req_stats.add('pre')
else:
if run_dict[tag].get('__state_ran__', True):
req_stats.add('met')
if r_state.endswith('_any') or r_state == 'onfail':
if 'met' in req_stats or 'change' in req_stats:
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onchangesmet' in req_stats:
if 'onchanges' in req_stats:
req_stats.remove('onchanges')
if 'fail' in req_stats:
req_stats.remove('fail')
if 'onfail' in req_stats:
# a met requisite in this case implies a success
if 'met' in req_stats:
req_stats.remove('onfail')
if r_state.endswith('_all'):
if 'onfail' in req_stats:
# a met requisite in this case implies a failure
if 'met' in req_stats:
req_stats.remove('met')
fun_stats.update(req_stats)
if 'unmet' in fun_stats:
status = 'unmet'
elif 'fail' in fun_stats:
status = 'fail'
elif 'pre' in fun_stats:
if 'premet' in fun_stats:
status = 'met'
else:
status = 'pre'
elif 'onfail' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onfail'
elif 'onchanges' in fun_stats and 'onchangesmet' not in fun_stats:
status = 'onchanges'
elif 'change' in fun_stats:
status = 'change'
else:
status = 'met'
return status, reqs
def event(self, chunk_ret, length, fire_event=False):
'''
Fire an event on the master bus
If `fire_event` is set to True an event will be sent with the
chunk name in the tag and the chunk result in the event data.
If `fire_event` is set to a string such as `mystate/is/finished`,
an event will be sent with the string added to the tag and the chunk
result in the event data.
If the `state_events` is set to True in the config, then after the
chunk is evaluated an event will be set up to the master with the
results.
'''
if not self.opts.get('local') and (self.opts.get('state_events', True) or fire_event):
if not self.opts.get('master_uri'):
ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event(
self.opts, self.opts['sock_dir'], listen=False).fire_event(ret, tag)
else:
ev_func = self.functions['event.fire_master']
ret = {'ret': chunk_ret}
if fire_event is True:
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(chunk_ret['name'])], 'state_result'
)
elif isinstance(fire_event, six.string_types):
tag = salt.utils.event.tagify(
[self.jid, self.opts['id'], six.text_type(fire_event)], 'state_result'
)
else:
tag = salt.utils.event.tagify(
[self.jid, 'prog', self.opts['id'], six.text_type(chunk_ret['__run_num__'])], 'job'
)
ret['len'] = length
preload = {'jid': self.jid}
ev_func(ret, tag, preload=preload)
def call_chunk(self, low, running, chunks):
'''
Check if a chunk has any requires, execute the requires and then
the chunk
'''
low = self._mod_aggregate(low, running, chunks)
self._mod_init(low)
tag = _gen_tag(low)
if not low.get('prerequired'):
self.active.add(tag)
requisites = ['require',
'require_any',
'watch',
'watch_any',
'prereq',
'onfail',
'onfail_any',
'onchanges',
'onchanges_any']
if not low.get('__prereq__'):
requisites.append('prerequired')
status, reqs = self.check_requisite(low, running, chunks, pre=True)
else:
status, reqs = self.check_requisite(low, running, chunks)
if status == 'unmet':
lost = {}
reqs = []
for requisite in requisites:
lost[requisite] = []
if requisite not in low:
continue
for req in low[requisite]:
if isinstance(req, six.string_types):
req = {'id': req}
req = trim_req(req)
found = False
req_key = next(iter(req))
req_val = req[req_key]
for chunk in chunks:
if req_val is None:
continue
if req_key == 'sls':
# Allow requisite tracking of entire sls files
if fnmatch.fnmatch(chunk['__sls__'], req_val):
if requisite == 'prereq':
chunk['__prereq__'] = True
reqs.append(chunk)
found = True
continue
if (fnmatch.fnmatch(chunk['name'], req_val) or
fnmatch.fnmatch(chunk['__id__'], req_val)):
if req_key == 'id' or chunk['state'] == req_key:
if requisite == 'prereq':
chunk['__prereq__'] = True
elif requisite == 'prerequired':
chunk['__prerequired__'] = True
reqs.append(chunk)
found = True
if not found:
lost[requisite].append(req)
if lost['require'] or lost['watch'] or lost['prereq'] \
or lost['onfail'] or lost['onchanges'] \
or lost.get('prerequired'):
comment = 'The following requisites were not found:\n'
for requisite, lreqs in six.iteritems(lost):
if not lreqs:
continue
comment += \
'{0}{1}:\n'.format(' ' * 19, requisite)
for lreq in lreqs:
req_key = next(iter(lreq))
req_val = lreq[req_key]
comment += \
'{0}{1}: {2}\n'.format(' ' * 23, req_key, req_val)
if low.get('__prereq__'):
run_dict = self.pre
else:
run_dict = running
start_time, duration = _calculate_fake_duration()
run_dict[tag] = {'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': comment,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(run_dict[tag], len(chunks), fire_event=low.get('fire_event'))
return running
for chunk in reqs:
# Check to see if the chunk has been run, only run it if
# it has not been run already
ctag = _gen_tag(chunk)
if ctag not in running:
if ctag in self.active:
if chunk.get('__prerequired__'):
# Prereq recusive, run this chunk with prereq on
if tag not in self.pre:
low['__prereq__'] = True
self.pre[ctag] = self.call(low, chunks, running)
return running
else:
return running
elif ctag not in running:
log.error('Recursive requisite found')
running[tag] = {
'changes': {},
'result': False,
'comment': 'Recursive requisite found',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
running = self.call_chunk(chunk, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
if low.get('__prereq__'):
status, reqs = self.check_requisite(low, running, chunks)
self.pre[tag] = self.call(low, chunks, running)
if not self.pre[tag]['changes'] and status == 'change':
self.pre[tag]['changes'] = {'watch': 'watch'}
self.pre[tag]['result'] = None
else:
running = self.call_chunk(low, running, chunks)
if self.check_failhard(chunk, running):
running['__FAILHARD__'] = True
return running
elif status == 'met':
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
elif status == 'fail':
# if the requisite that failed was due to a prereq on this low state
# show the normal error
if tag in self.pre:
running[tag] = self.pre[tag]
running[tag]['__run_num__'] = self.__run_num
running[tag]['__sls__'] = low['__sls__']
# otherwise the failure was due to a requisite down the chain
else:
# determine what the requisite failures where, and return
# a nice error message
failed_requisites = set()
# look at all requisite types for a failure
for req_lows in six.itervalues(reqs):
for req_low in req_lows:
req_tag = _gen_tag(req_low)
req_ret = self.pre.get(req_tag, running.get(req_tag))
# if there is no run output for the requisite it
# can't be the failure
if req_ret is None:
continue
# If the result was False (not None) it was a failure
if req_ret['result'] is False:
# use SLS.ID for the key-- so its easier to find
key = '{sls}.{_id}'.format(sls=req_low['__sls__'],
_id=req_low['__id__'])
failed_requisites.add(key)
_cmt = 'One or more requisite failed: {0}'.format(
', '.join(six.text_type(i) for i in failed_requisites)
)
start_time, duration = _calculate_fake_duration()
running[tag] = {
'changes': {},
'result': False,
'duration': duration,
'start_time': start_time,
'comment': _cmt,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']
}
self.pre[tag] = running[tag]
self.__run_num += 1
elif status == 'change' and not low.get('__prereq__'):
ret = self.call(low, chunks, running)
if not ret['changes'] and not ret.get('skip_watch', False):
low = low.copy()
low['sfun'] = low['fun']
low['fun'] = 'mod_watch'
low['__reqs__'] = reqs
ret = self.call(low, chunks, running)
running[tag] = ret
elif status == 'pre':
start_time, duration = _calculate_fake_duration()
pre_ret = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'No changes detected',
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
running[tag] = pre_ret
self.pre[tag] = pre_ret
self.__run_num += 1
elif status == 'onfail':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because onfail req did not change',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
elif status == 'onchanges':
start_time, duration = _calculate_fake_duration()
running[tag] = {'changes': {},
'result': True,
'duration': duration,
'start_time': start_time,
'comment': 'State was not run because none of the onchanges reqs changed',
'__state_ran__': False,
'__run_num__': self.__run_num,
'__sls__': low['__sls__']}
self.__run_num += 1
else:
if low.get('__prereq__'):
self.pre[tag] = self.call(low, chunks, running)
else:
running[tag] = self.call(low, chunks, running)
if tag in running:
running[tag]['__saltfunc__'] = '{0}.{1}'.format(low['state'], low['fun'])
self.event(running[tag], len(chunks), fire_event=low.get('fire_event'))
return running
def call_listen(self, chunks, running):
'''
Find all of the listen routines and call the associated mod_watch runs
'''
listeners = []
crefs = {}
for chunk in chunks:
crefs[(chunk['state'], chunk['__id__'], chunk['name'])] = chunk
if 'listen' in chunk:
listeners.append({(chunk['state'], chunk['__id__'], chunk['name']): chunk['listen']})
if 'listen_in' in chunk:
for l_in in chunk['listen_in']:
for key, val in six.iteritems(l_in):
listeners.append({(key, val, 'lookup'): [{chunk['state']: chunk['__id__']}]})
mod_watchers = []
errors = {}
for l_dict in listeners:
for key, val in six.iteritems(l_dict):
for listen_to in val:
if not isinstance(listen_to, dict):
found = False
for chunk in chunks:
if chunk['__id__'] == listen_to or \
chunk['name'] == listen_to:
listen_to = {chunk['state']: chunk['__id__']}
found = True
if not found:
continue
for lkey, lval in six.iteritems(listen_to):
if not any(lkey == cref[0] and lval in cref for cref in crefs):
rerror = {_l_tag(lkey, lval):
{
'comment': 'Referenced state {0}: {1} does not exist'.format(lkey, lval),
'name': 'listen_{0}:{1}'.format(lkey, lval),
'result': False,
'changes': {}
}}
errors.update(rerror)
continue
to_tags = [
_gen_tag(data) for cref, data in six.iteritems(crefs) if lkey == cref[0] and lval in cref
]
for to_tag in to_tags:
if to_tag not in running:
continue
if running[to_tag]['changes']:
if not any(key[0] == cref[0] and key[1] in cref for cref in crefs):
rerror = {_l_tag(key[0], key[1]):
{'comment': 'Referenced state {0}: {1} does not exist'.format(key[0], key[1]),
'name': 'listen_{0}:{1}'.format(key[0], key[1]),
'result': False,
'changes': {}}}
errors.update(rerror)
continue
new_chunks = [data for cref, data in six.iteritems(crefs) if key[0] == cref[0] and key[1] in cref]
for chunk in new_chunks:
low = chunk.copy()
low['sfun'] = chunk['fun']
low['fun'] = 'mod_watch'
low['__id__'] = 'listener_{0}'.format(low['__id__'])
for req in STATE_REQUISITE_KEYWORDS:
if req in low:
low.pop(req)
mod_watchers.append(low)
ret = self.call_chunks(mod_watchers)
running.update(ret)
for err in errors:
errors[err]['__run_num__'] = self.__run_num
self.__run_num += 1
running.update(errors)
return running
def inject_default_call(self, high):
'''
Sets .call function to a state, if not there.
:param high:
:return:
'''
for chunk in high:
state = high[chunk]
if not isinstance(state, collections.Mapping):
continue
for state_ref in state:
needs_default = True
if not isinstance(state[state_ref], list):
continue
for argset in state[state_ref]:
if isinstance(argset, six.string_types):
needs_default = False
break
if needs_default:
state[state_ref].insert(-1, '__call__')
def call_high(self, high, orchestration_jid=None):
'''
Process a high data call and ensure the defined states.
'''
self.inject_default_call(high)
errors = []
# If there is extension data reconcile it
high, ext_errors = self.reconcile_extend(high)
errors.extend(ext_errors)
errors.extend(self.verify_high(high))
if errors:
return errors
high, req_in_errors = self.requisite_in(high)
errors.extend(req_in_errors)
high = self.apply_exclude(high)
# Verify that the high data is structurally sound
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.compile_high_data(high, orchestration_jid)
# If there are extensions in the highstate, process them and update
# the low data chunks
if errors:
return errors
ret = self.call_chunks(chunks)
ret = self.call_listen(chunks, ret)
def _cleanup_accumulator_data():
accum_data_path = os.path.join(
get_accumulator_dir(self.opts['cachedir']),
self.instance_id
)
try:
os.remove(accum_data_path)
log.debug('Deleted accumulator data file %s', accum_data_path)
except OSError:
log.debug('File %s does not exist, no need to cleanup', accum_data_path)
_cleanup_accumulator_data()
if self.jid is not None:
pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)
if os.path.isfile(pause_path):
try:
os.remove(pause_path)
except OSError:
# File is not present, all is well
pass
return ret
def render_template(self, high, template):
errors = []
if not high:
return high, errors
if not isinstance(high, dict):
errors.append(
'Template {0} does not render to a dictionary'.format(template)
)
return high, errors
invalid_items = ('include', 'exclude', 'extends')
for item in invalid_items:
if item in high:
errors.append(
'The \'{0}\' declaration found on \'{1}\' is invalid when '
'rendering single templates'.format(item, template)
)
return high, errors
for name in high:
if not isinstance(high[name], dict):
if isinstance(high[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in high[name]:
comps = high[name].split('.')
high[name] = {
# '__sls__': template,
# '__env__': None,
comps[0]: [comps[1]]
}
continue
errors.append(
'ID {0} in template {1} is not a dictionary'.format(
name, template
)
)
continue
skeys = set()
for key in sorted(high[name]):
if key.startswith('_'):
continue
if high[name][key] is None:
errors.append(
'ID \'{0}\' in template {1} contains a short '
'declaration ({2}) with a trailing colon. When not '
'passing any arguments to a state, the colon must be '
'omitted.'.format(name, template, key)
)
continue
if not isinstance(high[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in template \'{1}\' contains multiple '
'state declarations of the same type'
.format(name, template)
)
continue
high[name][comps[0]] = high[name].pop(key)
high[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
return high, errors
def call_template(self, template):
'''
Enforce the states in a template
'''
high = compile_template(template,
self.rend,
self.opts['renderer'],
self.opts['renderer_blacklist'],
self.opts['renderer_whitelist'])
if not high:
return high
high, errors = self.render_template(high, template)
if errors:
return errors
return self.call_high(high)
|
saltstack/salt
|
salt/state.py
|
BaseHighState.__gen_opts
|
python
|
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
|
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L3124-L3169
|
[
"def create(path, saltenv=None):\n '''\n join `path` and `saltenv` into a 'salt://' URL.\n '''\n if salt.utils.platform.is_windows():\n path = salt.utils.path.sanitize_win_path(path)\n path = salt.utils.data.decode(path)\n\n query = 'saltenv={0}'.format(saltenv) if saltenv else ''\n url = salt.utils.data.decode(urlunparse(('file', '', path, '', query, '')))\n return 'salt://{0}'.format(url[len('file:///'):])\n"
] |
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
|
saltstack/salt
|
salt/state.py
|
BaseHighState._get_envs
|
python
|
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
|
Pull the file server environments out of the master options
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L3171-L3191
| null |
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
|
saltstack/salt
|
salt/state.py
|
BaseHighState.get_tops
|
python
|
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
|
Gather the top files
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L3193-L3313
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def compile_template(template,\n renderers,\n default,\n blacklist,\n whitelist,\n saltenv='base',\n sls='',\n input_data='',\n **kwargs):\n '''\n Take the path to a template and return the high data structure\n derived from the template.\n\n Helpers:\n\n :param mask_value:\n Mask value for debugging purposes (prevent sensitive information etc)\n example: \"mask_value=\"pass*\". All \"passwd\", \"password\", \"pass\" will\n be masked (as text).\n '''\n\n # if any error occurs, we return an empty dictionary\n ret = {}\n\n log.debug('compile template: %s', template)\n\n if 'env' in kwargs:\n # \"env\" is not supported; Use \"saltenv\".\n kwargs.pop('env')\n\n if template != ':string:':\n # Template was specified incorrectly\n if not isinstance(template, six.string_types):\n log.error('Template was specified incorrectly: %s', template)\n return ret\n # Template does not exist\n if not os.path.isfile(template):\n log.error('Template does not exist: %s', template)\n return ret\n # Template is an empty file\n if salt.utils.files.is_empty(template):\n log.debug('Template is an empty file: %s', template)\n return ret\n\n with codecs.open(template, encoding=SLS_ENCODING) as ifile:\n # data input to the first render function in the pipe\n input_data = ifile.read()\n if not input_data.strip():\n # Template is nothing but whitespace\n log.error('Template is nothing but whitespace: %s', template)\n return ret\n\n # Get the list of render funcs in the render pipe line.\n render_pipe = template_shebang(template, renderers, default, blacklist, whitelist, input_data)\n\n windows_newline = '\\r\\n' in input_data\n\n input_data = StringIO(input_data)\n for render, argline in render_pipe:\n if salt.utils.stringio.is_readable(input_data):\n input_data.seek(0) # pylint: disable=no-member\n render_kwargs = dict(renderers=renderers, tmplpath=template)\n render_kwargs.update(kwargs)\n if argline:\n render_kwargs['argline'] = argline\n start = time.time()\n ret = render(input_data, saltenv, sls, **render_kwargs)\n log.profile(\n 'Time (in seconds) to render \\'%s\\' using \\'%s\\' renderer: %s',\n template,\n render.__module__.split('.')[-1],\n time.time() - start\n )\n if ret is None:\n # The file is empty or is being written elsewhere\n time.sleep(0.01)\n ret = render(input_data, saltenv, sls, **render_kwargs)\n input_data = ret\n if log.isEnabledFor(logging.GARBAGE): # pylint: disable=no-member\n # If ret is not a StringIO (which means it was rendered using\n # yaml, mako, or another engine which renders to a data\n # structure) we don't want to log this.\n if salt.utils.stringio.is_readable(ret):\n log.debug('Rendered data from file: %s:\\n%s', template,\n salt.utils.sanitizers.mask_args_value(salt.utils.data.decode(ret.read()),\n kwargs.get('mask_value'))) # pylint: disable=no-member\n ret.seek(0) # pylint: disable=no-member\n\n # Preserve newlines from original template\n if windows_newline:\n if salt.utils.stringio.is_readable(ret):\n is_stringio = True\n contents = ret.read()\n else:\n is_stringio = False\n contents = ret\n\n if isinstance(contents, six.string_types):\n if '\\r\\n' not in contents:\n contents = contents.replace('\\n', '\\r\\n')\n ret = StringIO(contents) if is_stringio else contents\n else:\n if is_stringio:\n ret.seek(0)\n return ret\n",
"def pop(self, key, default=__marker):\n '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n If key is not found, d is returned if given, otherwise KeyError is raised.\n\n '''\n if key in self:\n result = self[key]\n del self[key]\n return result\n if default is self.__marker:\n raise KeyError(key)\n return default\n",
"def _get_envs(self):\n '''\n Pull the file server environments out of the master options\n '''\n envs = ['base']\n if 'file_roots' in self.opts:\n envs.extend([x for x in list(self.opts['file_roots'])\n if x not in envs])\n env_order = self.opts.get('env_order', [])\n # Remove duplicates while preserving the order\n members = set()\n env_order = [env for env in env_order if not (env in members or members.add(env))]\n client_envs = self.client.envs()\n if env_order and client_envs:\n return [env for env in env_order if env in client_envs]\n\n elif env_order:\n return env_order\n else:\n envs.extend([env for env in client_envs if env not in envs])\n return envs\n"
] |
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
|
saltstack/salt
|
salt/state.py
|
BaseHighState.merge_tops
|
python
|
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
|
Cleanly merge the top files
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L3315-L3333
|
[
"def _merge_tops_merge(self, tops):\n '''\n The default merging strategy. The base env is authoritative, so it is\n checked first, followed by the remaining environments. In top files\n from environments other than \"base\", only the section matching the\n environment from the top file will be considered, and it too will be\n ignored if that environment was defined in the \"base\" top file.\n '''\n top = DefaultOrderedDict(OrderedDict)\n\n # Check base env first as it is authoritative\n base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))\n for ctop in base_tops:\n for saltenv, targets in six.iteritems(ctop):\n if saltenv == 'include':\n continue\n try:\n for tgt in targets:\n top[saltenv][tgt] = ctop[saltenv][tgt]\n except TypeError:\n raise SaltRenderError('Unable to render top file. No targets found.')\n\n for cenv, ctops in six.iteritems(tops):\n for ctop in ctops:\n for saltenv, targets in six.iteritems(ctop):\n if saltenv == 'include':\n continue\n elif saltenv != cenv:\n log.debug(\n 'Section for saltenv \\'%s\\' in the \\'%s\\' '\n 'saltenv\\'s top file will be ignored, as the '\n 'top_file_merging_strategy is set to \\'merge\\' '\n 'and the saltenvs do not match',\n saltenv, cenv\n )\n continue\n elif saltenv in top:\n log.debug(\n 'Section for saltenv \\'%s\\' in the \\'%s\\' '\n 'saltenv\\'s top file will be ignored, as this '\n 'saltenv was already defined in the \\'base\\' top '\n 'file', saltenv, cenv\n )\n continue\n try:\n for tgt in targets:\n top[saltenv][tgt] = ctop[saltenv][tgt]\n except TypeError:\n raise SaltRenderError('Unable to render top file. No targets found.')\n return top\n"
] |
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
|
saltstack/salt
|
salt/state.py
|
BaseHighState._merge_tops_merge
|
python
|
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
|
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L3335-L3384
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n"
] |
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
|
saltstack/salt
|
salt/state.py
|
BaseHighState._merge_tops_same
|
python
|
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
|
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L3386-L3447
| null |
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
|
saltstack/salt
|
salt/state.py
|
BaseHighState._merge_tops_merge_all
|
python
|
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
|
Merge the top files into a single dictionary
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L3449-L3485
| null |
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
|
saltstack/salt
|
salt/state.py
|
BaseHighState.verify_tops
|
python
|
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
|
Verify the contents of the top file data
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L3487-L3536
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def itervalues(d, **kw):\n return d.itervalues(**kw)\n"
] |
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
|
saltstack/salt
|
salt/state.py
|
BaseHighState.get_top
|
python
|
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
|
Returns the high data derived from the top file
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L3538-L3547
|
[
"def get_tops(self):\n '''\n Gather the top files\n '''\n tops = DefaultOrderedDict(list)\n include = DefaultOrderedDict(list)\n done = DefaultOrderedDict(list)\n found = 0 # did we find any contents in the top files?\n # Gather initial top files\n merging_strategy = self.opts['top_file_merging_strategy']\n if merging_strategy == 'same' and not self.opts['saltenv']:\n if not self.opts['default_top']:\n raise SaltRenderError(\n 'top_file_merging_strategy set to \\'same\\', but no '\n 'default_top configuration option was set'\n )\n\n if self.opts['saltenv']:\n contents = self.client.cache_file(\n self.opts['state_top'],\n self.opts['saltenv']\n )\n if contents:\n found = 1\n tops[self.opts['saltenv']] = [\n compile_template(\n contents,\n self.state.rend,\n self.state.opts['renderer'],\n self.state.opts['renderer_blacklist'],\n self.state.opts['renderer_whitelist'],\n saltenv=self.opts['saltenv']\n )\n ]\n else:\n tops[self.opts['saltenv']] = [{}]\n\n else:\n found = 0\n state_top_saltenv = self.opts.get('state_top_saltenv', False)\n if state_top_saltenv \\\n and not isinstance(state_top_saltenv, six.string_types):\n state_top_saltenv = six.text_type(state_top_saltenv)\n\n for saltenv in [state_top_saltenv] if state_top_saltenv \\\n else self._get_envs():\n contents = self.client.cache_file(\n self.opts['state_top'],\n saltenv\n )\n if contents:\n found = found + 1\n tops[saltenv].append(\n compile_template(\n contents,\n self.state.rend,\n self.state.opts['renderer'],\n self.state.opts['renderer_blacklist'],\n self.state.opts['renderer_whitelist'],\n saltenv=saltenv\n )\n )\n else:\n tops[saltenv].append({})\n log.debug('No contents loaded for saltenv \\'%s\\'', saltenv)\n\n if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):\n log.warning(\n 'top_file_merging_strategy is set to \\'%s\\' and '\n 'multiple top files were found. Merging order is not '\n 'deterministic, it may be desirable to either set '\n 'top_file_merging_strategy to \\'same\\' or use the '\n '\\'env_order\\' configuration parameter to specify the '\n 'merging order.', merging_strategy\n )\n\n if found == 0:\n log.debug(\n 'No contents found in top file. If this is not expected, '\n 'verify that the \\'file_roots\\' specified in \\'etc/master\\' '\n 'are accessible. The \\'file_roots\\' configuration is: %s',\n repr(self.state.opts['file_roots'])\n )\n\n # Search initial top files for includes\n for saltenv, ctops in six.iteritems(tops):\n for ctop in ctops:\n if 'include' not in ctop:\n continue\n for sls in ctop['include']:\n include[saltenv].append(sls)\n ctop.pop('include')\n # Go through the includes and pull out the extra tops and add them\n while include:\n pops = []\n for saltenv, states in six.iteritems(include):\n pops.append(saltenv)\n if not states:\n continue\n for sls_match in states:\n for sls in fnmatch.filter(self.avail[saltenv], sls_match):\n if sls in done[saltenv]:\n continue\n tops[saltenv].append(\n compile_template(\n self.client.get_state(\n sls,\n saltenv\n ).get('dest', False),\n self.state.rend,\n self.state.opts['renderer'],\n self.state.opts['renderer_blacklist'],\n self.state.opts['renderer_whitelist'],\n saltenv\n )\n )\n done[saltenv].append(sls)\n for saltenv in pops:\n if saltenv in include:\n include.pop(saltenv)\n return tops\n",
"def merge_tops(self, tops):\n '''\n Cleanly merge the top files\n '''\n merging_strategy = self.opts['top_file_merging_strategy']\n try:\n merge_attr = '_merge_tops_{0}'.format(merging_strategy)\n merge_func = getattr(self, merge_attr)\n if not hasattr(merge_func, '__call__'):\n msg = '\\'{0}\\' is not callable'.format(merge_attr)\n log.error(msg)\n raise TypeError(msg)\n except (AttributeError, TypeError):\n log.warning(\n 'Invalid top_file_merging_strategy \\'%s\\', falling back to '\n '\\'merge\\'', merging_strategy\n )\n merge_func = self._merge_tops_merge\n return merge_func(tops)\n"
] |
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
|
saltstack/salt
|
salt/state.py
|
BaseHighState.top_matches
|
python
|
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
|
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L3549-L3601
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def _master_tops(self):\n '''\n Get results from the master_tops system. Override this function if the\n execution of the master_tops needs customization.\n '''\n return self.client.master_tops()\n",
"def _master_tops(self):\n '''\n Evaluate master_tops locally\n '''\n if 'id' not in self.opts:\n log.error('Received call for external nodes without an id')\n return {}\n if not salt.utils.verify.valid_id(self.opts, self.opts['id']):\n return {}\n # Evaluate all configured master_tops interfaces\n\n grains = {}\n ret = {}\n\n if 'grains' in self.opts:\n grains = self.opts['grains']\n for fun in self.tops:\n if fun not in self.opts.get('master_tops', {}):\n continue\n try:\n ret.update(self.tops[fun](opts=self.opts, grains=grains))\n except Exception as exc:\n # If anything happens in the top generation, log it and move on\n log.error(\n 'Top function %s failed with error %s for minion %s',\n fun, exc, self.opts['id']\n )\n return ret\n",
"def _filter_matches(_match, _data, _opts):\n if isinstance(_data, six.string_types):\n _data = [_data]\n if self.matchers['confirm_top.confirm_top'](\n _match,\n _data,\n _opts\n ):\n if saltenv not in matches:\n matches[saltenv] = []\n for item in _data:\n if 'subfilter' in item:\n _tmpdata = item.pop('subfilter')\n for match, data in six.iteritems(_tmpdata):\n _filter_matches(match, data, _opts)\n if isinstance(item, six.string_types):\n matches[saltenv].append(item)\n elif isinstance(item, dict):\n env_key, inc_sls = item.popitem()\n if env_key not in self.avail:\n continue\n if env_key not in matches:\n matches[env_key] = []\n matches[env_key].append(inc_sls)\n"
] |
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
|
saltstack/salt
|
salt/state.py
|
BaseHighState.load_dynamic
|
python
|
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
|
If autoload_dynamic_modules is True then automatically load the
dynamic modules
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L3610-L3622
| null |
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
|
saltstack/salt
|
salt/state.py
|
BaseHighState.render_state
|
python
|
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
|
Render a state file and retrieve all of the include states
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L3624-L3807
|
[
"def compile_template(template,\n renderers,\n default,\n blacklist,\n whitelist,\n saltenv='base',\n sls='',\n input_data='',\n **kwargs):\n '''\n Take the path to a template and return the high data structure\n derived from the template.\n\n Helpers:\n\n :param mask_value:\n Mask value for debugging purposes (prevent sensitive information etc)\n example: \"mask_value=\"pass*\". All \"passwd\", \"password\", \"pass\" will\n be masked (as text).\n '''\n\n # if any error occurs, we return an empty dictionary\n ret = {}\n\n log.debug('compile template: %s', template)\n\n if 'env' in kwargs:\n # \"env\" is not supported; Use \"saltenv\".\n kwargs.pop('env')\n\n if template != ':string:':\n # Template was specified incorrectly\n if not isinstance(template, six.string_types):\n log.error('Template was specified incorrectly: %s', template)\n return ret\n # Template does not exist\n if not os.path.isfile(template):\n log.error('Template does not exist: %s', template)\n return ret\n # Template is an empty file\n if salt.utils.files.is_empty(template):\n log.debug('Template is an empty file: %s', template)\n return ret\n\n with codecs.open(template, encoding=SLS_ENCODING) as ifile:\n # data input to the first render function in the pipe\n input_data = ifile.read()\n if not input_data.strip():\n # Template is nothing but whitespace\n log.error('Template is nothing but whitespace: %s', template)\n return ret\n\n # Get the list of render funcs in the render pipe line.\n render_pipe = template_shebang(template, renderers, default, blacklist, whitelist, input_data)\n\n windows_newline = '\\r\\n' in input_data\n\n input_data = StringIO(input_data)\n for render, argline in render_pipe:\n if salt.utils.stringio.is_readable(input_data):\n input_data.seek(0) # pylint: disable=no-member\n render_kwargs = dict(renderers=renderers, tmplpath=template)\n render_kwargs.update(kwargs)\n if argline:\n render_kwargs['argline'] = argline\n start = time.time()\n ret = render(input_data, saltenv, sls, **render_kwargs)\n log.profile(\n 'Time (in seconds) to render \\'%s\\' using \\'%s\\' renderer: %s',\n template,\n render.__module__.split('.')[-1],\n time.time() - start\n )\n if ret is None:\n # The file is empty or is being written elsewhere\n time.sleep(0.01)\n ret = render(input_data, saltenv, sls, **render_kwargs)\n input_data = ret\n if log.isEnabledFor(logging.GARBAGE): # pylint: disable=no-member\n # If ret is not a StringIO (which means it was rendered using\n # yaml, mako, or another engine which renders to a data\n # structure) we don't want to log this.\n if salt.utils.stringio.is_readable(ret):\n log.debug('Rendered data from file: %s:\\n%s', template,\n salt.utils.sanitizers.mask_args_value(salt.utils.data.decode(ret.read()),\n kwargs.get('mask_value'))) # pylint: disable=no-member\n ret.seek(0) # pylint: disable=no-member\n\n # Preserve newlines from original template\n if windows_newline:\n if salt.utils.stringio.is_readable(ret):\n is_stringio = True\n contents = ret.read()\n else:\n is_stringio = False\n contents = ret\n\n if isinstance(contents, six.string_types):\n if '\\r\\n' not in contents:\n contents = contents.replace('\\n', '\\r\\n')\n ret = StringIO(contents) if is_stringio else contents\n else:\n if is_stringio:\n ret.seek(0)\n return ret\n",
"def render_state(self, sls, saltenv, mods, matches, local=False):\n '''\n Render a state file and retrieve all of the include states\n '''\n errors = []\n if not local:\n state_data = self.client.get_state(sls, saltenv)\n fn_ = state_data.get('dest', False)\n else:\n fn_ = sls\n if not os.path.isfile(fn_):\n errors.append(\n 'Specified SLS {0} on local filesystem cannot '\n 'be found.'.format(sls)\n )\n state = None\n if not fn_:\n errors.append(\n 'Specified SLS {0} in saltenv {1} is not '\n 'available on the salt master or through a configured '\n 'fileserver'.format(sls, saltenv)\n )\n else:\n try:\n state = compile_template(fn_,\n self.state.rend,\n self.state.opts['renderer'],\n self.state.opts['renderer_blacklist'],\n self.state.opts['renderer_whitelist'],\n saltenv,\n sls,\n rendered_sls=mods\n )\n except SaltRenderError as exc:\n msg = 'Rendering SLS \\'{0}:{1}\\' failed: {2}'.format(\n saltenv, sls, exc\n )\n log.critical(msg)\n errors.append(msg)\n except Exception as exc:\n msg = 'Rendering SLS {0} failed, render error: {1}'.format(\n sls, exc\n )\n log.critical(\n msg,\n # Show the traceback if the debug logging level is enabled\n exc_info_on_loglevel=logging.DEBUG\n )\n errors.append('{0}\\n{1}'.format(msg, traceback.format_exc()))\n try:\n mods.add('{0}:{1}'.format(saltenv, sls))\n except AttributeError:\n pass\n\n if state:\n if not isinstance(state, dict):\n errors.append(\n 'SLS {0} does not render to a dictionary'.format(sls)\n )\n else:\n include = []\n if 'include' in state:\n if not isinstance(state['include'], list):\n err = ('Include Declaration in SLS {0} is not formed '\n 'as a list'.format(sls))\n errors.append(err)\n else:\n include = state.pop('include')\n\n self._handle_extend(state, sls, saltenv, errors)\n self._handle_exclude(state, sls, saltenv, errors)\n self._handle_state_decls(state, sls, saltenv, errors)\n\n for inc_sls in include:\n # inc_sls may take the form of:\n # 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}\n # {<env_key>: 'sls.to.include'}\n # {'_xenv': 'sls.to.resolve'}\n xenv_key = '_xenv'\n\n if isinstance(inc_sls, dict):\n env_key, inc_sls = inc_sls.popitem()\n else:\n env_key = saltenv\n\n if env_key not in self.avail:\n msg = ('Nonexistent saltenv \\'{0}\\' found in include '\n 'of \\'{1}\\' within SLS \\'{2}:{3}\\''\n .format(env_key, inc_sls, saltenv, sls))\n log.error(msg)\n errors.append(msg)\n continue\n\n if inc_sls.startswith('.'):\n match = re.match(r'^(\\.+)(.*)$', inc_sls)\n if match:\n levels, include = match.groups()\n else:\n msg = ('Badly formatted include {0} found in include '\n 'in SLS \\'{2}:{3}\\''\n .format(inc_sls, saltenv, sls))\n log.error(msg)\n errors.append(msg)\n continue\n level_count = len(levels)\n p_comps = sls.split('.')\n if state_data.get('source', '').endswith('/init.sls'):\n p_comps.append('init')\n if level_count > len(p_comps):\n msg = ('Attempted relative include of \\'{0}\\' '\n 'within SLS \\'{1}:{2}\\' '\n 'goes beyond top level package '\n .format(inc_sls, saltenv, sls))\n log.error(msg)\n errors.append(msg)\n continue\n inc_sls = '.'.join(p_comps[:-level_count] + [include])\n\n if env_key != xenv_key:\n if matches is None:\n matches = []\n # Resolve inc_sls in the specified environment\n if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):\n resolved_envs = [env_key]\n else:\n resolved_envs = []\n else:\n # Resolve inc_sls in the subset of environment matches\n resolved_envs = [\n aenv for aenv in matches\n if fnmatch.filter(self.avail[aenv], inc_sls)\n ]\n\n # An include must be resolved to a single environment, or\n # the include must exist in the current environment\n if len(resolved_envs) == 1 or saltenv in resolved_envs:\n # Match inc_sls against the available states in the\n # resolved env, matching wildcards in the process. If\n # there were no matches, then leave inc_sls as the\n # target so that the next recursion of render_state\n # will recognize the error.\n sls_targets = fnmatch.filter(\n self.avail[saltenv],\n inc_sls\n ) or [inc_sls]\n\n for sls_target in sls_targets:\n r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv\n mod_tgt = '{0}:{1}'.format(r_env, sls_target)\n if mod_tgt not in mods:\n nstate, err = self.render_state(\n sls_target,\n r_env,\n mods,\n matches\n )\n if nstate:\n self.merge_included_states(state, nstate, errors)\n state.update(nstate)\n if err:\n errors.extend(err)\n else:\n msg = ''\n if not resolved_envs:\n msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '\n 'master in saltenv(s): {2} '\n ).format(env_key,\n inc_sls,\n ', '.join(matches) if env_key == xenv_key else env_key)\n elif len(resolved_envs) > 1:\n msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '\n 'in multiple available saltenvs: {2}'\n ).format(env_key,\n inc_sls,\n ', '.join(resolved_envs))\n log.critical(msg)\n errors.append(msg)\n try:\n self._handle_iorder(state)\n except TypeError:\n log.critical('Could not render SLS %s. Syntax error detected.', sls)\n else:\n state = {}\n return state, errors\n",
"def _handle_iorder(self, state):\n '''\n Take a state and apply the iorder system\n '''\n if self.opts['state_auto_order']:\n for name in state:\n for s_dec in state[name]:\n if not isinstance(s_dec, six.string_types):\n # PyDSL OrderedDict?\n continue\n\n if not isinstance(state[name], dict):\n # Include's or excludes as lists?\n continue\n if not isinstance(state[name][s_dec], list):\n # Bad syntax, let the verify seq pick it up later on\n continue\n\n found = False\n if s_dec.startswith('_'):\n continue\n\n for arg in state[name][s_dec]:\n if isinstance(arg, dict):\n if arg:\n if next(six.iterkeys(arg)) == 'order':\n found = True\n if not found:\n if not isinstance(state[name][s_dec], list):\n # quite certainly a syntax error, managed elsewhere\n continue\n state[name][s_dec].append(\n {'order': self.iorder}\n )\n self.iorder += 1\n return state\n",
"def _handle_state_decls(self, state, sls, saltenv, errors):\n '''\n Add sls and saltenv components to the state\n '''\n for name in state:\n if not isinstance(state[name], dict):\n if name == '__extend__':\n continue\n if name == '__exclude__':\n continue\n\n if isinstance(state[name], six.string_types):\n # Is this is a short state, it needs to be padded\n if '.' in state[name]:\n comps = state[name].split('.')\n state[name] = {'__sls__': sls,\n '__env__': saltenv,\n comps[0]: [comps[1]]}\n continue\n errors.append(\n 'ID {0} in SLS {1} is not a dictionary'.format(name, sls)\n )\n continue\n skeys = set()\n for key in list(state[name]):\n if key.startswith('_'):\n continue\n if not isinstance(state[name][key], list):\n continue\n if '.' in key:\n comps = key.split('.')\n # Salt doesn't support state files such as:\n #\n # /etc/redis/redis.conf:\n # file.managed:\n # - source: salt://redis/redis.conf\n # - user: redis\n # - group: redis\n # - mode: 644\n # file.comment:\n # - regex: ^requirepass\n if comps[0] in skeys:\n errors.append(\n 'ID \\'{0}\\' in SLS \\'{1}\\' contains multiple state '\n 'declarations of the same type'.format(name, sls)\n )\n continue\n state[name][comps[0]] = state[name].pop(key)\n state[name][comps[0]].append(comps[1])\n skeys.add(comps[0])\n continue\n skeys.add(key)\n if '__sls__' not in state[name]:\n state[name]['__sls__'] = sls\n if '__env__' not in state[name]:\n state[name]['__env__'] = saltenv\n",
"def _handle_extend(self, state, sls, saltenv, errors):\n '''\n Take the extend dec out of state and apply to the highstate global\n dec\n '''\n if 'extend' in state:\n ext = state.pop('extend')\n if not isinstance(ext, dict):\n errors.append(('Extension value in SLS \\'{0}\\' is not a '\n 'dictionary').format(sls))\n return\n for name in ext:\n if not isinstance(ext[name], dict):\n errors.append(('Extension name \\'{0}\\' in SLS \\'{1}\\' is '\n 'not a dictionary'\n .format(name, sls)))\n continue\n if '__sls__' not in ext[name]:\n ext[name]['__sls__'] = sls\n if '__env__' not in ext[name]:\n ext[name]['__env__'] = saltenv\n for key in list(ext[name]):\n if key.startswith('_'):\n continue\n if not isinstance(ext[name][key], list):\n continue\n if '.' in key:\n comps = key.split('.')\n ext[name][comps[0]] = ext[name].pop(key)\n ext[name][comps[0]].append(comps[1])\n state.setdefault('__extend__', []).append(ext)\n",
"def _handle_exclude(self, state, sls, saltenv, errors):\n '''\n Take the exclude dec out of the state and apply it to the highstate\n global dec\n '''\n if 'exclude' in state:\n exc = state.pop('exclude')\n if not isinstance(exc, list):\n err = ('Exclude Declaration in SLS {0} is not formed '\n 'as a list'.format(sls))\n errors.append(err)\n state.setdefault('__exclude__', []).extend(exc)\n",
"def merge_included_states(self, highstate, state, errors):\n # The extend members can not be treated as globally unique:\n if '__extend__' in state:\n highstate.setdefault('__extend__',\n []).extend(state.pop('__extend__'))\n if '__exclude__' in state:\n highstate.setdefault('__exclude__',\n []).extend(state.pop('__exclude__'))\n for id_ in state:\n if id_ in highstate:\n if highstate[id_] != state[id_]:\n errors.append((\n 'Detected conflicting IDs, SLS'\n ' IDs need to be globally unique.\\n The'\n ' conflicting ID is \\'{0}\\' and is found in SLS'\n ' \\'{1}:{2}\\' and SLS \\'{3}:{4}\\'').format(\n id_,\n highstate[id_]['__env__'],\n highstate[id_]['__sls__'],\n state[id_]['__env__'],\n state[id_]['__sls__'])\n )\n try:\n highstate.update(state)\n except ValueError:\n errors.append(\n 'Error when rendering state with contents: {0}'.format(state)\n )\n"
] |
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
|
saltstack/salt
|
salt/state.py
|
BaseHighState._handle_iorder
|
python
|
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
|
Take a state and apply the iorder system
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L3809-L3844
| null |
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
|
saltstack/salt
|
salt/state.py
|
BaseHighState._handle_state_decls
|
python
|
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
|
Add sls and saltenv components to the state
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L3846-L3901
| null |
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
|
saltstack/salt
|
salt/state.py
|
BaseHighState._handle_extend
|
python
|
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
|
Take the extend dec out of state and apply to the highstate global
dec
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L3903-L3933
| null |
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
|
saltstack/salt
|
salt/state.py
|
BaseHighState._handle_exclude
|
python
|
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
|
Take the exclude dec out of the state and apply it to the highstate
global dec
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L3935-L3946
| null |
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
|
saltstack/salt
|
salt/state.py
|
BaseHighState.render_highstate
|
python
|
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
|
Gather the state files and render them into a single unified salt
high data structure.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L3948-L3995
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def render_state(self, sls, saltenv, mods, matches, local=False):\n '''\n Render a state file and retrieve all of the include states\n '''\n errors = []\n if not local:\n state_data = self.client.get_state(sls, saltenv)\n fn_ = state_data.get('dest', False)\n else:\n fn_ = sls\n if not os.path.isfile(fn_):\n errors.append(\n 'Specified SLS {0} on local filesystem cannot '\n 'be found.'.format(sls)\n )\n state = None\n if not fn_:\n errors.append(\n 'Specified SLS {0} in saltenv {1} is not '\n 'available on the salt master or through a configured '\n 'fileserver'.format(sls, saltenv)\n )\n else:\n try:\n state = compile_template(fn_,\n self.state.rend,\n self.state.opts['renderer'],\n self.state.opts['renderer_blacklist'],\n self.state.opts['renderer_whitelist'],\n saltenv,\n sls,\n rendered_sls=mods\n )\n except SaltRenderError as exc:\n msg = 'Rendering SLS \\'{0}:{1}\\' failed: {2}'.format(\n saltenv, sls, exc\n )\n log.critical(msg)\n errors.append(msg)\n except Exception as exc:\n msg = 'Rendering SLS {0} failed, render error: {1}'.format(\n sls, exc\n )\n log.critical(\n msg,\n # Show the traceback if the debug logging level is enabled\n exc_info_on_loglevel=logging.DEBUG\n )\n errors.append('{0}\\n{1}'.format(msg, traceback.format_exc()))\n try:\n mods.add('{0}:{1}'.format(saltenv, sls))\n except AttributeError:\n pass\n\n if state:\n if not isinstance(state, dict):\n errors.append(\n 'SLS {0} does not render to a dictionary'.format(sls)\n )\n else:\n include = []\n if 'include' in state:\n if not isinstance(state['include'], list):\n err = ('Include Declaration in SLS {0} is not formed '\n 'as a list'.format(sls))\n errors.append(err)\n else:\n include = state.pop('include')\n\n self._handle_extend(state, sls, saltenv, errors)\n self._handle_exclude(state, sls, saltenv, errors)\n self._handle_state_decls(state, sls, saltenv, errors)\n\n for inc_sls in include:\n # inc_sls may take the form of:\n # 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}\n # {<env_key>: 'sls.to.include'}\n # {'_xenv': 'sls.to.resolve'}\n xenv_key = '_xenv'\n\n if isinstance(inc_sls, dict):\n env_key, inc_sls = inc_sls.popitem()\n else:\n env_key = saltenv\n\n if env_key not in self.avail:\n msg = ('Nonexistent saltenv \\'{0}\\' found in include '\n 'of \\'{1}\\' within SLS \\'{2}:{3}\\''\n .format(env_key, inc_sls, saltenv, sls))\n log.error(msg)\n errors.append(msg)\n continue\n\n if inc_sls.startswith('.'):\n match = re.match(r'^(\\.+)(.*)$', inc_sls)\n if match:\n levels, include = match.groups()\n else:\n msg = ('Badly formatted include {0} found in include '\n 'in SLS \\'{2}:{3}\\''\n .format(inc_sls, saltenv, sls))\n log.error(msg)\n errors.append(msg)\n continue\n level_count = len(levels)\n p_comps = sls.split('.')\n if state_data.get('source', '').endswith('/init.sls'):\n p_comps.append('init')\n if level_count > len(p_comps):\n msg = ('Attempted relative include of \\'{0}\\' '\n 'within SLS \\'{1}:{2}\\' '\n 'goes beyond top level package '\n .format(inc_sls, saltenv, sls))\n log.error(msg)\n errors.append(msg)\n continue\n inc_sls = '.'.join(p_comps[:-level_count] + [include])\n\n if env_key != xenv_key:\n if matches is None:\n matches = []\n # Resolve inc_sls in the specified environment\n if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):\n resolved_envs = [env_key]\n else:\n resolved_envs = []\n else:\n # Resolve inc_sls in the subset of environment matches\n resolved_envs = [\n aenv for aenv in matches\n if fnmatch.filter(self.avail[aenv], inc_sls)\n ]\n\n # An include must be resolved to a single environment, or\n # the include must exist in the current environment\n if len(resolved_envs) == 1 or saltenv in resolved_envs:\n # Match inc_sls against the available states in the\n # resolved env, matching wildcards in the process. If\n # there were no matches, then leave inc_sls as the\n # target so that the next recursion of render_state\n # will recognize the error.\n sls_targets = fnmatch.filter(\n self.avail[saltenv],\n inc_sls\n ) or [inc_sls]\n\n for sls_target in sls_targets:\n r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv\n mod_tgt = '{0}:{1}'.format(r_env, sls_target)\n if mod_tgt not in mods:\n nstate, err = self.render_state(\n sls_target,\n r_env,\n mods,\n matches\n )\n if nstate:\n self.merge_included_states(state, nstate, errors)\n state.update(nstate)\n if err:\n errors.extend(err)\n else:\n msg = ''\n if not resolved_envs:\n msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '\n 'master in saltenv(s): {2} '\n ).format(env_key,\n inc_sls,\n ', '.join(matches) if env_key == xenv_key else env_key)\n elif len(resolved_envs) > 1:\n msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '\n 'in multiple available saltenvs: {2}'\n ).format(env_key,\n inc_sls,\n ', '.join(resolved_envs))\n log.critical(msg)\n errors.append(msg)\n try:\n self._handle_iorder(state)\n except TypeError:\n log.critical('Could not render SLS %s. Syntax error detected.', sls)\n else:\n state = {}\n return state, errors\n",
"def clean_duplicate_extends(self, highstate):\n if '__extend__' in highstate:\n highext = []\n for items in (six.iteritems(ext) for ext in highstate['__extend__']):\n for item in items:\n if item not in highext:\n highext.append(item)\n highstate['__extend__'] = [{t[0]: t[1]} for t in highext]\n",
"def merge_included_states(self, highstate, state, errors):\n # The extend members can not be treated as globally unique:\n if '__extend__' in state:\n highstate.setdefault('__extend__',\n []).extend(state.pop('__extend__'))\n if '__exclude__' in state:\n highstate.setdefault('__exclude__',\n []).extend(state.pop('__exclude__'))\n for id_ in state:\n if id_ in highstate:\n if highstate[id_] != state[id_]:\n errors.append((\n 'Detected conflicting IDs, SLS'\n ' IDs need to be globally unique.\\n The'\n ' conflicting ID is \\'{0}\\' and is found in SLS'\n ' \\'{1}:{2}\\' and SLS \\'{3}:{4}\\'').format(\n id_,\n highstate[id_]['__env__'],\n highstate[id_]['__sls__'],\n state[id_]['__env__'],\n state[id_]['__sls__'])\n )\n try:\n highstate.update(state)\n except ValueError:\n errors.append(\n 'Error when rendering state with contents: {0}'.format(state)\n )\n"
] |
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
|
saltstack/salt
|
salt/state.py
|
BaseHighState._check_pillar
|
python
|
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
|
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L4035-L4044
| null |
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
|
saltstack/salt
|
salt/state.py
|
BaseHighState.matches_whitelist
|
python
|
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
|
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L4046-L4061
| null |
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
|
saltstack/salt
|
salt/state.py
|
BaseHighState.call_highstate
|
python
|
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
|
Run the sequence to execute the salt highstate for this minion
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L4063-L4142
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def load(self, fn_):\n '''\n Run the correct serialization to load a file\n '''\n data = fn_.read()\n fn_.close()\n if data:\n if six.PY3:\n return self.loads(data, encoding='utf-8')\n else:\n return self.loads(data)\n",
"def call_high(self, high, orchestration_jid=None):\n '''\n Process a high data call and ensure the defined states.\n '''\n self.inject_default_call(high)\n errors = []\n # If there is extension data reconcile it\n high, ext_errors = self.reconcile_extend(high)\n errors.extend(ext_errors)\n errors.extend(self.verify_high(high))\n if errors:\n return errors\n high, req_in_errors = self.requisite_in(high)\n errors.extend(req_in_errors)\n high = self.apply_exclude(high)\n # Verify that the high data is structurally sound\n if errors:\n return errors\n # Compile and verify the raw chunks\n chunks = self.compile_high_data(high, orchestration_jid)\n\n # If there are extensions in the highstate, process them and update\n # the low data chunks\n if errors:\n return errors\n ret = self.call_chunks(chunks)\n ret = self.call_listen(chunks, ret)\n\n def _cleanup_accumulator_data():\n accum_data_path = os.path.join(\n get_accumulator_dir(self.opts['cachedir']),\n self.instance_id\n )\n try:\n os.remove(accum_data_path)\n log.debug('Deleted accumulator data file %s', accum_data_path)\n except OSError:\n log.debug('File %s does not exist, no need to cleanup', accum_data_path)\n _cleanup_accumulator_data()\n if self.jid is not None:\n pause_path = os.path.join(self.opts['cachedir'], 'state_pause', self.jid)\n if os.path.isfile(pause_path):\n try:\n os.remove(pause_path)\n except OSError:\n # File is not present, all is well\n pass\n\n return ret\n",
"def verify_tops(self, tops):\n '''\n Verify the contents of the top file data\n '''\n errors = []\n if not isinstance(tops, dict):\n errors.append('Top data was not formed as a dict')\n # No further checks will work, bail out\n return errors\n for saltenv, matches in six.iteritems(tops):\n if saltenv == 'include':\n continue\n if not isinstance(saltenv, six.string_types):\n errors.append(\n 'Environment {0} in top file is not formed as a '\n 'string'.format(saltenv)\n )\n if saltenv == '':\n errors.append('Empty saltenv statement in top file')\n if not isinstance(matches, dict):\n errors.append(\n 'The top file matches for saltenv {0} are not '\n 'formatted as a dict'.format(saltenv)\n )\n for slsmods in six.itervalues(matches):\n if not isinstance(slsmods, list):\n errors.append('Malformed topfile (state declarations not '\n 'formed as a list)')\n continue\n for slsmod in slsmods:\n if isinstance(slsmod, dict):\n # This value is a match option\n for val in six.itervalues(slsmod):\n if not val:\n errors.append(\n 'Improperly formatted top file matcher '\n 'in saltenv {0}: {1} file'.format(\n slsmod,\n val\n )\n )\n elif isinstance(slsmod, six.string_types):\n # This is a sls module\n if not slsmod:\n errors.append(\n 'Environment {0} contains an empty sls '\n 'index'.format(saltenv)\n )\n\n return errors\n",
"def get_top(self):\n '''\n Returns the high data derived from the top file\n '''\n try:\n tops = self.get_tops()\n except SaltRenderError as err:\n log.error('Unable to render top file: %s', err.error)\n return {}\n return self.merge_tops(tops)\n",
"def top_matches(self, top):\n '''\n Search through the top high data for matches and return the states\n that this minion needs to execute.\n\n Returns:\n {'saltenv': ['state1', 'state2', ...]}\n '''\n matches = DefaultOrderedDict(OrderedDict)\n # pylint: disable=cell-var-from-loop\n for saltenv, body in six.iteritems(top):\n if self.opts['saltenv']:\n if saltenv != self.opts['saltenv']:\n continue\n for match, data in six.iteritems(body):\n def _filter_matches(_match, _data, _opts):\n if isinstance(_data, six.string_types):\n _data = [_data]\n if self.matchers['confirm_top.confirm_top'](\n _match,\n _data,\n _opts\n ):\n if saltenv not in matches:\n matches[saltenv] = []\n for item in _data:\n if 'subfilter' in item:\n _tmpdata = item.pop('subfilter')\n for match, data in six.iteritems(_tmpdata):\n _filter_matches(match, data, _opts)\n if isinstance(item, six.string_types):\n matches[saltenv].append(item)\n elif isinstance(item, dict):\n env_key, inc_sls = item.popitem()\n if env_key not in self.avail:\n continue\n if env_key not in matches:\n matches[env_key] = []\n matches[env_key].append(inc_sls)\n _filter_matches(match, data, self.opts['nodegroups'])\n ext_matches = self._master_tops()\n for saltenv in ext_matches:\n top_file_matches = matches.get(saltenv, [])\n if self.opts.get('master_tops_first'):\n first = ext_matches[saltenv]\n second = top_file_matches\n else:\n first = top_file_matches\n second = ext_matches[saltenv]\n matches[saltenv] = first + [x for x in second if x not in first]\n\n # pylint: enable=cell-var-from-loop\n return matches\n",
"def load_dynamic(self, matches):\n '''\n If autoload_dynamic_modules is True then automatically load the\n dynamic modules\n '''\n if not self.opts['autoload_dynamic_modules']:\n return\n syncd = self.state.functions['saltutil.sync_all'](list(matches),\n refresh=False)\n if syncd['grains']:\n self.opts['grains'] = salt.loader.grains(self.opts)\n self.state.opts['pillar'] = self.state._gather_pillar()\n self.state.module_refresh()\n",
"def _check_pillar(self, force=False):\n '''\n Check the pillar for errors, refuse to run the state if there are\n errors in the pillar and return the pillar errors\n '''\n if force:\n return True\n if '_errors' in self.state.opts['pillar']:\n return False\n return True\n",
"def matches_whitelist(self, matches, whitelist):\n '''\n Reads over the matches and returns a matches dict with just the ones\n that are in the whitelist\n '''\n if not whitelist:\n return matches\n ret_matches = {}\n if not isinstance(whitelist, list):\n whitelist = whitelist.split(',')\n for env in matches:\n for sls in matches[env]:\n if sls in whitelist:\n ret_matches[env] = ret_matches[env] if env in ret_matches else []\n ret_matches[env].append(sls)\n return ret_matches\n"
] |
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
|
saltstack/salt
|
salt/state.py
|
BaseHighState.compile_highstate
|
python
|
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
|
Return just the highstate or the errors
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L4144-L4158
|
[
"def verify_tops(self, tops):\n '''\n Verify the contents of the top file data\n '''\n errors = []\n if not isinstance(tops, dict):\n errors.append('Top data was not formed as a dict')\n # No further checks will work, bail out\n return errors\n for saltenv, matches in six.iteritems(tops):\n if saltenv == 'include':\n continue\n if not isinstance(saltenv, six.string_types):\n errors.append(\n 'Environment {0} in top file is not formed as a '\n 'string'.format(saltenv)\n )\n if saltenv == '':\n errors.append('Empty saltenv statement in top file')\n if not isinstance(matches, dict):\n errors.append(\n 'The top file matches for saltenv {0} are not '\n 'formatted as a dict'.format(saltenv)\n )\n for slsmods in six.itervalues(matches):\n if not isinstance(slsmods, list):\n errors.append('Malformed topfile (state declarations not '\n 'formed as a list)')\n continue\n for slsmod in slsmods:\n if isinstance(slsmod, dict):\n # This value is a match option\n for val in six.itervalues(slsmod):\n if not val:\n errors.append(\n 'Improperly formatted top file matcher '\n 'in saltenv {0}: {1} file'.format(\n slsmod,\n val\n )\n )\n elif isinstance(slsmod, six.string_types):\n # This is a sls module\n if not slsmod:\n errors.append(\n 'Environment {0} contains an empty sls '\n 'index'.format(saltenv)\n )\n\n return errors\n",
"def get_top(self):\n '''\n Returns the high data derived from the top file\n '''\n try:\n tops = self.get_tops()\n except SaltRenderError as err:\n log.error('Unable to render top file: %s', err.error)\n return {}\n return self.merge_tops(tops)\n",
"def top_matches(self, top):\n '''\n Search through the top high data for matches and return the states\n that this minion needs to execute.\n\n Returns:\n {'saltenv': ['state1', 'state2', ...]}\n '''\n matches = DefaultOrderedDict(OrderedDict)\n # pylint: disable=cell-var-from-loop\n for saltenv, body in six.iteritems(top):\n if self.opts['saltenv']:\n if saltenv != self.opts['saltenv']:\n continue\n for match, data in six.iteritems(body):\n def _filter_matches(_match, _data, _opts):\n if isinstance(_data, six.string_types):\n _data = [_data]\n if self.matchers['confirm_top.confirm_top'](\n _match,\n _data,\n _opts\n ):\n if saltenv not in matches:\n matches[saltenv] = []\n for item in _data:\n if 'subfilter' in item:\n _tmpdata = item.pop('subfilter')\n for match, data in six.iteritems(_tmpdata):\n _filter_matches(match, data, _opts)\n if isinstance(item, six.string_types):\n matches[saltenv].append(item)\n elif isinstance(item, dict):\n env_key, inc_sls = item.popitem()\n if env_key not in self.avail:\n continue\n if env_key not in matches:\n matches[env_key] = []\n matches[env_key].append(inc_sls)\n _filter_matches(match, data, self.opts['nodegroups'])\n ext_matches = self._master_tops()\n for saltenv in ext_matches:\n top_file_matches = matches.get(saltenv, [])\n if self.opts.get('master_tops_first'):\n first = ext_matches[saltenv]\n second = top_file_matches\n else:\n first = top_file_matches\n second = ext_matches[saltenv]\n matches[saltenv] = first + [x for x in second if x not in first]\n\n # pylint: enable=cell-var-from-loop\n return matches\n",
"def render_highstate(self, matches):\n '''\n Gather the state files and render them into a single unified salt\n high data structure.\n '''\n highstate = self.building_highstate\n all_errors = []\n mods = set()\n statefiles = []\n for saltenv, states in six.iteritems(matches):\n for sls_match in states:\n if saltenv in self.avail:\n statefiles = fnmatch.filter(self.avail[saltenv], sls_match)\n elif '__env__' in self.avail:\n statefiles = fnmatch.filter(self.avail['__env__'], sls_match)\n else:\n all_errors.append(\n 'No matching salt environment for environment '\n '\\'{0}\\' found'.format(saltenv)\n )\n # if we did not found any sls in the fileserver listing, this\n # may be because the sls was generated or added later, we can\n # try to directly execute it, and if it fails, anyway it will\n # return the former error\n if not statefiles:\n statefiles = [sls_match]\n\n for sls in statefiles:\n r_env = '{0}:{1}'.format(saltenv, sls)\n if r_env in mods:\n continue\n state, errors = self.render_state(\n sls, saltenv, mods, matches)\n if state:\n self.merge_included_states(highstate, state, errors)\n for i, error in enumerate(errors[:]):\n if 'is not available' in error:\n # match SLS foobar in environment\n this_sls = 'SLS {0} in saltenv'.format(\n sls_match)\n if this_sls in error:\n errors[i] = (\n 'No matching sls found for \\'{0}\\' '\n 'in env \\'{1}\\''.format(sls_match, saltenv))\n all_errors.extend(errors)\n\n self.clean_duplicate_extends(highstate)\n return highstate, all_errors\n"
] |
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
|
saltstack/salt
|
salt/state.py
|
BaseHighState.compile_low_chunks
|
python
|
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
|
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L4160-L4185
|
[
"def verify_high(self, high):\n '''\n Verify that the high data is viable and follows the data structure\n '''\n errors = []\n if not isinstance(high, dict):\n errors.append('High data is not a dictionary and is invalid')\n reqs = OrderedDict()\n for name, body in six.iteritems(high):\n try:\n if name.startswith('__'):\n continue\n except AttributeError:\n pass\n if not isinstance(name, six.string_types):\n errors.append(\n 'ID \\'{0}\\' in SLS \\'{1}\\' is not formed as a string, but '\n 'is a {2}. It may need to be quoted.'.format(\n name, body['__sls__'], type(name).__name__)\n )\n if not isinstance(body, dict):\n err = ('The type {0} in {1} is not formatted as a dictionary'\n .format(name, body))\n errors.append(err)\n continue\n for state in body:\n if state.startswith('__'):\n continue\n if body[state] is None:\n errors.append(\n 'ID \\'{0}\\' in SLS \\'{1}\\' contains a short declaration '\n '({2}) with a trailing colon. When not passing any '\n 'arguments to a state, the colon must be omitted.'\n .format(name, body['__sls__'], state)\n )\n continue\n if not isinstance(body[state], list):\n errors.append(\n 'State \\'{0}\\' in SLS \\'{1}\\' is not formed as a list'\n .format(name, body['__sls__'])\n )\n else:\n fun = 0\n if '.' in state:\n fun += 1\n for arg in body[state]:\n if isinstance(arg, six.string_types):\n fun += 1\n if ' ' in arg.strip():\n errors.append(('The function \"{0}\" in state '\n '\"{1}\" in SLS \"{2}\" has '\n 'whitespace, a function with whitespace is '\n 'not supported, perhaps this is an argument '\n 'that is missing a \":\"').format(\n arg,\n name,\n body['__sls__']))\n elif isinstance(arg, dict):\n # The arg is a dict, if the arg is require or\n # watch, it must be a list.\n #\n # Add the requires to the reqs dict and check them\n # all for recursive requisites.\n argfirst = next(iter(arg))\n if argfirst == 'names':\n if not isinstance(arg[argfirst], list):\n errors.append(\n 'The \\'names\\' argument in state '\n '\\'{0}\\' in SLS \\'{1}\\' needs to be '\n 'formed as a list'\n .format(name, body['__sls__'])\n )\n if argfirst in ('require', 'watch', 'prereq', 'onchanges'):\n if not isinstance(arg[argfirst], list):\n errors.append(\n 'The {0} statement in state \\'{1}\\' in '\n 'SLS \\'{2}\\' needs to be formed as a '\n 'list'.format(argfirst,\n name,\n body['__sls__'])\n )\n # It is a list, verify that the members of the\n # list are all single key dicts.\n else:\n reqs[name] = OrderedDict(state=state)\n for req in arg[argfirst]:\n if isinstance(req, six.string_types):\n req = {'id': req}\n if not isinstance(req, dict):\n err = ('Requisite declaration {0}'\n ' in SLS {1} is not formed as a'\n ' single key dictionary').format(\n req,\n body['__sls__'])\n errors.append(err)\n continue\n req_key = next(iter(req))\n req_val = req[req_key]\n if '.' in req_key:\n errors.append(\n 'Invalid requisite type \\'{0}\\' '\n 'in state \\'{1}\\', in SLS '\n '\\'{2}\\'. Requisite types must '\n 'not contain dots, did you '\n 'mean \\'{3}\\'?'.format(\n req_key,\n name,\n body['__sls__'],\n req_key[:req_key.find('.')]\n )\n )\n if not ishashable(req_val):\n errors.append((\n 'Illegal requisite \"{0}\", '\n 'please check your syntax.\\n'\n ).format(req_val))\n continue\n\n # Check for global recursive requisites\n reqs[name][req_val] = req_key\n # I am going beyond 80 chars on\n # purpose, this is just too much\n # of a pain to deal with otherwise\n if req_val in reqs:\n if name in reqs[req_val]:\n if reqs[req_val][name] == state:\n if reqs[req_val]['state'] == reqs[name][req_val]:\n err = ('A recursive '\n 'requisite was found, SLS '\n '\"{0}\" ID \"{1}\" ID \"{2}\"'\n ).format(\n body['__sls__'],\n name,\n req_val\n )\n errors.append(err)\n # Make sure that there is only one key in the\n # dict\n if len(list(arg)) != 1:\n errors.append(\n 'Multiple dictionaries defined in '\n 'argument of state \\'{0}\\' in SLS \\'{1}\\''\n .format(name, body['__sls__'])\n )\n if not fun:\n if state == 'require' or state == 'watch':\n continue\n errors.append(\n 'No function declared in state \\'{0}\\' in SLS \\'{1}\\''\n .format(state, body['__sls__'])\n )\n elif fun > 1:\n errors.append(\n 'Too many functions declared in state \\'{0}\\' in '\n 'SLS \\'{1}\\''.format(state, body['__sls__'])\n )\n return errors\n",
"def reconcile_extend(self, high):\n '''\n Pull the extend data and add it to the respective high data\n '''\n errors = []\n if '__extend__' not in high:\n return high, errors\n ext = high.pop('__extend__')\n for ext_chunk in ext:\n for name, body in six.iteritems(ext_chunk):\n if name not in high:\n state_type = next(\n x for x in body if not x.startswith('__')\n )\n # Check for a matching 'name' override in high data\n ids = find_name(name, state_type, high)\n if len(ids) != 1:\n errors.append(\n 'Cannot extend ID \\'{0}\\' in \\'{1}:{2}\\'. It is not '\n 'part of the high state.\\n'\n 'This is likely due to a missing include statement '\n 'or an incorrectly typed ID.\\nEnsure that a '\n 'state with an ID of \\'{0}\\' is available\\nin '\n 'environment \\'{1}\\' and to SLS \\'{2}\\''.format(\n name,\n body.get('__env__', 'base'),\n body.get('__sls__', 'base'))\n )\n continue\n else:\n name = ids[0][0]\n\n for state, run in six.iteritems(body):\n if state.startswith('__'):\n continue\n if state not in high[name]:\n high[name][state] = run\n continue\n # high[name][state] is extended by run, both are lists\n for arg in run:\n update = False\n for hind in range(len(high[name][state])):\n if isinstance(arg, six.string_types) and isinstance(high[name][state][hind], six.string_types):\n # replacing the function, replace the index\n high[name][state].pop(hind)\n high[name][state].insert(hind, arg)\n update = True\n continue\n if isinstance(arg, dict) and isinstance(high[name][state][hind], dict):\n # It is an option, make sure the options match\n argfirst = next(iter(arg))\n if argfirst == next(iter(high[name][state][hind])):\n # If argfirst is a requisite then we must merge\n # our requisite with that of the target state\n if argfirst in STATE_REQUISITE_KEYWORDS:\n high[name][state][hind][argfirst].extend(arg[argfirst])\n # otherwise, its not a requisite and we are just extending (replacing)\n else:\n high[name][state][hind] = arg\n update = True\n if (argfirst == 'name' and\n next(iter(high[name][state][hind])) == 'names'):\n # If names are overwritten by name use the name\n high[name][state][hind] = arg\n if not update:\n high[name][state].append(arg)\n return high, errors\n",
"def apply_exclude(self, high):\n '''\n Read in the __exclude__ list and remove all excluded objects from the\n high data\n '''\n if '__exclude__' not in high:\n return high\n ex_sls = set()\n ex_id = set()\n exclude = high.pop('__exclude__')\n for exc in exclude:\n if isinstance(exc, six.string_types):\n # The exclude statement is a string, assume it is an sls\n ex_sls.add(exc)\n if isinstance(exc, dict):\n # Explicitly declared exclude\n if len(exc) != 1:\n continue\n key = next(six.iterkeys(exc))\n if key == 'sls':\n ex_sls.add(exc['sls'])\n elif key == 'id':\n ex_id.add(exc['id'])\n # Now the excludes have been simplified, use them\n if ex_sls:\n # There are sls excludes, find the associated ids\n for name, body in six.iteritems(high):\n if name.startswith('__'):\n continue\n sls = body.get('__sls__', '')\n if not sls:\n continue\n for ex_ in ex_sls:\n if fnmatch.fnmatch(sls, ex_):\n ex_id.add(name)\n for id_ in ex_id:\n if id_ in high:\n high.pop(id_)\n return high\n",
"def requisite_in(self, high):\n '''\n Extend the data reference with requisite_in arguments\n '''\n req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'}\n req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'})\n extend = {}\n errors = []\n disabled_reqs = self.opts.get('disabled_requisites', [])\n if not isinstance(disabled_reqs, list):\n disabled_reqs = [disabled_reqs]\n for id_, body in six.iteritems(high):\n if not isinstance(body, dict):\n continue\n for state, run in six.iteritems(body):\n if state.startswith('__'):\n continue\n for arg in run:\n if isinstance(arg, dict):\n # It is not a function, verify that the arg is a\n # requisite in statement\n if not arg:\n # Empty arg dict\n # How did we get this far?\n continue\n # Split out the components\n key = next(iter(arg))\n if key not in req_in:\n continue\n if key in disabled_reqs:\n log.warning('The %s requisite has been disabled, Ignoring.', key)\n continue\n rkey = key.split('_')[0]\n items = arg[key]\n if isinstance(items, dict):\n # Formatted as a single req_in\n for _state, name in six.iteritems(items):\n\n # Not a use requisite_in\n found = False\n if name not in extend:\n extend[name] = OrderedDict()\n if '.' in _state:\n errors.append(\n 'Invalid requisite in {0}: {1} for '\n '{2}, in SLS \\'{3}\\'. Requisites must '\n 'not contain dots, did you mean \\'{4}\\'?'\n .format(\n rkey,\n _state,\n name,\n body['__sls__'],\n _state[:_state.find('.')]\n )\n )\n _state = _state.split('.')[0]\n if _state not in extend[name]:\n extend[name][_state] = []\n extend[name]['__env__'] = body['__env__']\n extend[name]['__sls__'] = body['__sls__']\n for ind in range(len(extend[name][_state])):\n if next(iter(\n extend[name][_state][ind])) == rkey:\n # Extending again\n extend[name][_state][ind][rkey].append(\n {state: id_}\n )\n found = True\n if found:\n continue\n # The rkey is not present yet, create it\n extend[name][_state].append(\n {rkey: [{state: id_}]}\n )\n\n if isinstance(items, list):\n # Formed as a list of requisite additions\n hinges = []\n for ind in items:\n if not isinstance(ind, dict):\n # Malformed req_in\n if ind in high:\n _ind_high = [x for x\n in high[ind]\n if not x.startswith('__')]\n ind = {_ind_high[0]: ind}\n else:\n found = False\n for _id in iter(high):\n for state in [state for state\n in iter(high[_id])\n if not state.startswith('__')]:\n for j in iter(high[_id][state]):\n if isinstance(j, dict) and 'name' in j:\n if j['name'] == ind:\n ind = {state: _id}\n found = True\n if not found:\n continue\n if not ind:\n continue\n pstate = next(iter(ind))\n pname = ind[pstate]\n if pstate == 'sls':\n # Expand hinges here\n hinges = find_sls_ids(pname, high)\n else:\n hinges.append((pname, pstate))\n if '.' in pstate:\n errors.append(\n 'Invalid requisite in {0}: {1} for '\n '{2}, in SLS \\'{3}\\'. Requisites must '\n 'not contain dots, did you mean \\'{4}\\'?'\n .format(\n rkey,\n pstate,\n pname,\n body['__sls__'],\n pstate[:pstate.find('.')]\n )\n )\n pstate = pstate.split(\".\")[0]\n for tup in hinges:\n name, _state = tup\n if key == 'prereq_in':\n # Add prerequired to origin\n if id_ not in extend:\n extend[id_] = OrderedDict()\n if state not in extend[id_]:\n extend[id_][state] = []\n extend[id_][state].append(\n {'prerequired': [{_state: name}]}\n )\n if key == 'prereq':\n # Add prerequired to prereqs\n ext_ids = find_name(name, _state, high)\n for ext_id, _req_state in ext_ids:\n if ext_id not in extend:\n extend[ext_id] = OrderedDict()\n if _req_state not in extend[ext_id]:\n extend[ext_id][_req_state] = []\n extend[ext_id][_req_state].append(\n {'prerequired': [{state: id_}]}\n )\n continue\n if key == 'use_in':\n # Add the running states args to the\n # use_in states\n ext_ids = find_name(name, _state, high)\n for ext_id, _req_state in ext_ids:\n if not ext_id:\n continue\n ext_args = state_args(ext_id, _state, high)\n if ext_id not in extend:\n extend[ext_id] = OrderedDict()\n if _req_state not in extend[ext_id]:\n extend[ext_id][_req_state] = []\n ignore_args = req_in_all.union(ext_args)\n for arg in high[id_][state]:\n if not isinstance(arg, dict):\n continue\n if len(arg) != 1:\n continue\n if next(iter(arg)) in ignore_args:\n continue\n # Don't use name or names\n if next(six.iterkeys(arg)) == 'name':\n continue\n if next(six.iterkeys(arg)) == 'names':\n continue\n extend[ext_id][_req_state].append(arg)\n continue\n if key == 'use':\n # Add the use state's args to the\n # running state\n ext_ids = find_name(name, _state, high)\n for ext_id, _req_state in ext_ids:\n if not ext_id:\n continue\n loc_args = state_args(id_, state, high)\n if id_ not in extend:\n extend[id_] = OrderedDict()\n if state not in extend[id_]:\n extend[id_][state] = []\n ignore_args = req_in_all.union(loc_args)\n for arg in high[ext_id][_req_state]:\n if not isinstance(arg, dict):\n continue\n if len(arg) != 1:\n continue\n if next(iter(arg)) in ignore_args:\n continue\n # Don't use name or names\n if next(six.iterkeys(arg)) == 'name':\n continue\n if next(six.iterkeys(arg)) == 'names':\n continue\n extend[id_][state].append(arg)\n continue\n found = False\n if name not in extend:\n extend[name] = OrderedDict()\n if _state not in extend[name]:\n extend[name][_state] = []\n extend[name]['__env__'] = body['__env__']\n extend[name]['__sls__'] = body['__sls__']\n for ind in range(len(extend[name][_state])):\n if next(iter(\n extend[name][_state][ind])) == rkey:\n # Extending again\n extend[name][_state][ind][rkey].append(\n {state: id_}\n )\n found = True\n if found:\n continue\n # The rkey is not present yet, create it\n extend[name][_state].append(\n {rkey: [{state: id_}]}\n )\n high['__extend__'] = []\n for key, val in six.iteritems(extend):\n high['__extend__'].append({key: val})\n req_in_high, req_in_errors = self.reconcile_extend(high)\n errors.extend(req_in_errors)\n return req_in_high, errors\n",
"def get_top(self):\n '''\n Returns the high data derived from the top file\n '''\n try:\n tops = self.get_tops()\n except SaltRenderError as err:\n log.error('Unable to render top file: %s', err.error)\n return {}\n return self.merge_tops(tops)\n",
"def top_matches(self, top):\n '''\n Search through the top high data for matches and return the states\n that this minion needs to execute.\n\n Returns:\n {'saltenv': ['state1', 'state2', ...]}\n '''\n matches = DefaultOrderedDict(OrderedDict)\n # pylint: disable=cell-var-from-loop\n for saltenv, body in six.iteritems(top):\n if self.opts['saltenv']:\n if saltenv != self.opts['saltenv']:\n continue\n for match, data in six.iteritems(body):\n def _filter_matches(_match, _data, _opts):\n if isinstance(_data, six.string_types):\n _data = [_data]\n if self.matchers['confirm_top.confirm_top'](\n _match,\n _data,\n _opts\n ):\n if saltenv not in matches:\n matches[saltenv] = []\n for item in _data:\n if 'subfilter' in item:\n _tmpdata = item.pop('subfilter')\n for match, data in six.iteritems(_tmpdata):\n _filter_matches(match, data, _opts)\n if isinstance(item, six.string_types):\n matches[saltenv].append(item)\n elif isinstance(item, dict):\n env_key, inc_sls = item.popitem()\n if env_key not in self.avail:\n continue\n if env_key not in matches:\n matches[env_key] = []\n matches[env_key].append(inc_sls)\n _filter_matches(match, data, self.opts['nodegroups'])\n ext_matches = self._master_tops()\n for saltenv in ext_matches:\n top_file_matches = matches.get(saltenv, [])\n if self.opts.get('master_tops_first'):\n first = ext_matches[saltenv]\n second = top_file_matches\n else:\n first = top_file_matches\n second = ext_matches[saltenv]\n matches[saltenv] = first + [x for x in second if x not in first]\n\n # pylint: enable=cell-var-from-loop\n return matches\n",
"def render_highstate(self, matches):\n '''\n Gather the state files and render them into a single unified salt\n high data structure.\n '''\n highstate = self.building_highstate\n all_errors = []\n mods = set()\n statefiles = []\n for saltenv, states in six.iteritems(matches):\n for sls_match in states:\n if saltenv in self.avail:\n statefiles = fnmatch.filter(self.avail[saltenv], sls_match)\n elif '__env__' in self.avail:\n statefiles = fnmatch.filter(self.avail['__env__'], sls_match)\n else:\n all_errors.append(\n 'No matching salt environment for environment '\n '\\'{0}\\' found'.format(saltenv)\n )\n # if we did not found any sls in the fileserver listing, this\n # may be because the sls was generated or added later, we can\n # try to directly execute it, and if it fails, anyway it will\n # return the former error\n if not statefiles:\n statefiles = [sls_match]\n\n for sls in statefiles:\n r_env = '{0}:{1}'.format(saltenv, sls)\n if r_env in mods:\n continue\n state, errors = self.render_state(\n sls, saltenv, mods, matches)\n if state:\n self.merge_included_states(highstate, state, errors)\n for i, error in enumerate(errors[:]):\n if 'is not available' in error:\n # match SLS foobar in environment\n this_sls = 'SLS {0} in saltenv'.format(\n sls_match)\n if this_sls in error:\n errors[i] = (\n 'No matching sls found for \\'{0}\\' '\n 'in env \\'{1}\\''.format(sls_match, saltenv))\n all_errors.extend(errors)\n\n self.clean_duplicate_extends(highstate)\n return highstate, all_errors\n"
] |
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
|
saltstack/salt
|
salt/state.py
|
BaseHighState.compile_state_usage
|
python
|
def compile_state_usage(self):
'''
Return all used and unused states for the minion based on the top match data
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
if err:
return err
matches = self.top_matches(top)
state_usage = {}
for saltenv, states in self.avail.items():
env_usage = {
'used': [],
'unused': [],
'count_all': 0,
'count_used': 0,
'count_unused': 0
}
env_matches = matches.get(saltenv)
for state in states:
env_usage['count_all'] += 1
if state in env_matches:
env_usage['count_used'] += 1
env_usage['used'].append(state)
else:
env_usage['count_unused'] += 1
env_usage['unused'].append(state)
state_usage[saltenv] = env_usage
return state_usage
|
Return all used and unused states for the minion based on the top match data
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L4187-L4223
|
[
"def verify_tops(self, tops):\n '''\n Verify the contents of the top file data\n '''\n errors = []\n if not isinstance(tops, dict):\n errors.append('Top data was not formed as a dict')\n # No further checks will work, bail out\n return errors\n for saltenv, matches in six.iteritems(tops):\n if saltenv == 'include':\n continue\n if not isinstance(saltenv, six.string_types):\n errors.append(\n 'Environment {0} in top file is not formed as a '\n 'string'.format(saltenv)\n )\n if saltenv == '':\n errors.append('Empty saltenv statement in top file')\n if not isinstance(matches, dict):\n errors.append(\n 'The top file matches for saltenv {0} are not '\n 'formatted as a dict'.format(saltenv)\n )\n for slsmods in six.itervalues(matches):\n if not isinstance(slsmods, list):\n errors.append('Malformed topfile (state declarations not '\n 'formed as a list)')\n continue\n for slsmod in slsmods:\n if isinstance(slsmod, dict):\n # This value is a match option\n for val in six.itervalues(slsmod):\n if not val:\n errors.append(\n 'Improperly formatted top file matcher '\n 'in saltenv {0}: {1} file'.format(\n slsmod,\n val\n )\n )\n elif isinstance(slsmod, six.string_types):\n # This is a sls module\n if not slsmod:\n errors.append(\n 'Environment {0} contains an empty sls '\n 'index'.format(saltenv)\n )\n\n return errors\n",
"def get_top(self):\n '''\n Returns the high data derived from the top file\n '''\n try:\n tops = self.get_tops()\n except SaltRenderError as err:\n log.error('Unable to render top file: %s', err.error)\n return {}\n return self.merge_tops(tops)\n",
"def top_matches(self, top):\n '''\n Search through the top high data for matches and return the states\n that this minion needs to execute.\n\n Returns:\n {'saltenv': ['state1', 'state2', ...]}\n '''\n matches = DefaultOrderedDict(OrderedDict)\n # pylint: disable=cell-var-from-loop\n for saltenv, body in six.iteritems(top):\n if self.opts['saltenv']:\n if saltenv != self.opts['saltenv']:\n continue\n for match, data in six.iteritems(body):\n def _filter_matches(_match, _data, _opts):\n if isinstance(_data, six.string_types):\n _data = [_data]\n if self.matchers['confirm_top.confirm_top'](\n _match,\n _data,\n _opts\n ):\n if saltenv not in matches:\n matches[saltenv] = []\n for item in _data:\n if 'subfilter' in item:\n _tmpdata = item.pop('subfilter')\n for match, data in six.iteritems(_tmpdata):\n _filter_matches(match, data, _opts)\n if isinstance(item, six.string_types):\n matches[saltenv].append(item)\n elif isinstance(item, dict):\n env_key, inc_sls = item.popitem()\n if env_key not in self.avail:\n continue\n if env_key not in matches:\n matches[env_key] = []\n matches[env_key].append(inc_sls)\n _filter_matches(match, data, self.opts['nodegroups'])\n ext_matches = self._master_tops()\n for saltenv in ext_matches:\n top_file_matches = matches.get(saltenv, [])\n if self.opts.get('master_tops_first'):\n first = ext_matches[saltenv]\n second = top_file_matches\n else:\n first = top_file_matches\n second = ext_matches[saltenv]\n matches[saltenv] = first + [x for x in second if x not in first]\n\n # pylint: enable=cell-var-from-loop\n return matches\n"
] |
class BaseHighState(object):
'''
The BaseHighState is an abstract base class that is the foundation of
running a highstate, extend it and add a self.state object of type State.
When extending this class, please note that ``self.client`` and
``self.matcher`` should be instantiated and handled.
'''
def __init__(self, opts):
self.opts = self.__gen_opts(opts)
self.iorder = 10000
self.avail = self.__gather_avail()
self.serial = salt.payload.Serial(self.opts)
self.building_highstate = OrderedDict()
def __gather_avail(self):
'''
Gather the lists of available sls data from the master
'''
avail = {}
for saltenv in self._get_envs():
avail[saltenv] = self.client.list_states(saltenv)
return avail
def __gen_opts(self, opts):
'''
The options used by the High State object are derived from options
on the minion and the master, or just the minion if the high state
call is entirely local.
'''
# If the state is intended to be applied locally, then the local opts
# should have all of the needed data, otherwise overwrite the local
# data items with data from the master
if 'local_state' in opts:
if opts['local_state']:
return opts
mopts = self.client.master_opts()
if not isinstance(mopts, dict):
# An error happened on the master
opts['renderer'] = 'jinja|yaml'
opts['failhard'] = False
opts['state_top'] = salt.utils.url.create('top.sls')
opts['nodegroups'] = {}
opts['file_roots'] = {'base': [syspaths.BASE_FILE_ROOTS_DIR]}
else:
opts['renderer'] = mopts['renderer']
opts['failhard'] = mopts.get('failhard', False)
if mopts['state_top'].startswith('salt://'):
opts['state_top'] = mopts['state_top']
elif mopts['state_top'].startswith('/'):
opts['state_top'] = salt.utils.url.create(mopts['state_top'][1:])
else:
opts['state_top'] = salt.utils.url.create(mopts['state_top'])
opts['state_top_saltenv'] = mopts.get('state_top_saltenv', None)
opts['nodegroups'] = mopts.get('nodegroups', {})
opts['state_auto_order'] = mopts.get(
'state_auto_order',
opts['state_auto_order'])
opts['file_roots'] = mopts['file_roots']
opts['top_file_merging_strategy'] = mopts.get('top_file_merging_strategy',
opts.get('top_file_merging_strategy'))
opts['env_order'] = mopts.get('env_order', opts.get('env_order', []))
opts['default_top'] = mopts.get('default_top', opts.get('default_top'))
opts['state_events'] = mopts.get('state_events')
opts['state_aggregate'] = mopts.get('state_aggregate', opts.get('state_aggregate', False))
opts['jinja_env'] = mopts.get('jinja_env', {})
opts['jinja_sls_env'] = mopts.get('jinja_sls_env', {})
opts['jinja_lstrip_blocks'] = mopts.get('jinja_lstrip_blocks', False)
opts['jinja_trim_blocks'] = mopts.get('jinja_trim_blocks', False)
return opts
def _get_envs(self):
'''
Pull the file server environments out of the master options
'''
envs = ['base']
if 'file_roots' in self.opts:
envs.extend([x for x in list(self.opts['file_roots'])
if x not in envs])
env_order = self.opts.get('env_order', [])
# Remove duplicates while preserving the order
members = set()
env_order = [env for env in env_order if not (env in members or members.add(env))]
client_envs = self.client.envs()
if env_order and client_envs:
return [env for env in env_order if env in client_envs]
elif env_order:
return env_order
else:
envs.extend([env for env in client_envs if env not in envs])
return envs
def get_tops(self):
'''
Gather the top files
'''
tops = DefaultOrderedDict(list)
include = DefaultOrderedDict(list)
done = DefaultOrderedDict(list)
found = 0 # did we find any contents in the top files?
# Gather initial top files
merging_strategy = self.opts['top_file_merging_strategy']
if merging_strategy == 'same' and not self.opts['saltenv']:
if not self.opts['default_top']:
raise SaltRenderError(
'top_file_merging_strategy set to \'same\', but no '
'default_top configuration option was set'
)
if self.opts['saltenv']:
contents = self.client.cache_file(
self.opts['state_top'],
self.opts['saltenv']
)
if contents:
found = 1
tops[self.opts['saltenv']] = [
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=self.opts['saltenv']
)
]
else:
tops[self.opts['saltenv']] = [{}]
else:
found = 0
state_top_saltenv = self.opts.get('state_top_saltenv', False)
if state_top_saltenv \
and not isinstance(state_top_saltenv, six.string_types):
state_top_saltenv = six.text_type(state_top_saltenv)
for saltenv in [state_top_saltenv] if state_top_saltenv \
else self._get_envs():
contents = self.client.cache_file(
self.opts['state_top'],
saltenv
)
if contents:
found = found + 1
tops[saltenv].append(
compile_template(
contents,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv=saltenv
)
)
else:
tops[saltenv].append({})
log.debug('No contents loaded for saltenv \'%s\'', saltenv)
if found > 1 and merging_strategy == 'merge' and not self.opts.get('env_order', None):
log.warning(
'top_file_merging_strategy is set to \'%s\' and '
'multiple top files were found. Merging order is not '
'deterministic, it may be desirable to either set '
'top_file_merging_strategy to \'same\' or use the '
'\'env_order\' configuration parameter to specify the '
'merging order.', merging_strategy
)
if found == 0:
log.debug(
'No contents found in top file. If this is not expected, '
'verify that the \'file_roots\' specified in \'etc/master\' '
'are accessible. The \'file_roots\' configuration is: %s',
repr(self.state.opts['file_roots'])
)
# Search initial top files for includes
for saltenv, ctops in six.iteritems(tops):
for ctop in ctops:
if 'include' not in ctop:
continue
for sls in ctop['include']:
include[saltenv].append(sls)
ctop.pop('include')
# Go through the includes and pull out the extra tops and add them
while include:
pops = []
for saltenv, states in six.iteritems(include):
pops.append(saltenv)
if not states:
continue
for sls_match in states:
for sls in fnmatch.filter(self.avail[saltenv], sls_match):
if sls in done[saltenv]:
continue
tops[saltenv].append(
compile_template(
self.client.get_state(
sls,
saltenv
).get('dest', False),
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv
)
)
done[saltenv].append(sls)
for saltenv in pops:
if saltenv in include:
include.pop(saltenv)
return tops
def merge_tops(self, tops):
'''
Cleanly merge the top files
'''
merging_strategy = self.opts['top_file_merging_strategy']
try:
merge_attr = '_merge_tops_{0}'.format(merging_strategy)
merge_func = getattr(self, merge_attr)
if not hasattr(merge_func, '__call__'):
msg = '\'{0}\' is not callable'.format(merge_attr)
log.error(msg)
raise TypeError(msg)
except (AttributeError, TypeError):
log.warning(
'Invalid top_file_merging_strategy \'%s\', falling back to '
'\'merge\'', merging_strategy
)
merge_func = self._merge_tops_merge
return merge_func(tops)
def _merge_tops_merge(self, tops):
'''
The default merging strategy. The base env is authoritative, so it is
checked first, followed by the remaining environments. In top files
from environments other than "base", only the section matching the
environment from the top file will be considered, and it too will be
ignored if that environment was defined in the "base" top file.
'''
top = DefaultOrderedDict(OrderedDict)
# Check base env first as it is authoritative
base_tops = tops.pop('base', DefaultOrderedDict(OrderedDict))
for ctop in base_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
for cenv, ctops in six.iteritems(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'merge\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
elif saltenv in top:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as this '
'saltenv was already defined in the \'base\' top '
'file', saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_same(self, tops):
'''
For each saltenv, only consider the top file from that saltenv. All
sections matching a given saltenv, which appear in a different
saltenv's top file, will be ignored.
'''
top = DefaultOrderedDict(OrderedDict)
for cenv, ctops in six.iteritems(tops):
if all([x == {} for x in ctops]):
# No top file found in this env, check the default_top
default_top = self.opts['default_top']
fallback_tops = tops.get(default_top, [])
if all([x == {} for x in fallback_tops]):
# Nothing in the fallback top file
log.error(
'The \'%s\' saltenv has no top file, and the fallback '
'saltenv specified by default_top (%s) also has no '
'top file', cenv, default_top
)
continue
for ctop in fallback_tops:
for saltenv, targets in six.iteritems(ctop):
if saltenv != cenv:
continue
log.debug(
'The \'%s\' saltenv has no top file, using the '
'default_top saltenv (%s)', cenv, default_top
)
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
break
else:
log.error(
'The \'%s\' saltenv has no top file, and no '
'matches were found in the top file for the '
'default_top saltenv (%s)', cenv, default_top
)
continue
else:
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
elif saltenv != cenv:
log.debug(
'Section for saltenv \'%s\' in the \'%s\' '
'saltenv\'s top file will be ignored, as the '
'top_file_merging_strategy is set to \'same\' '
'and the saltenvs do not match',
saltenv, cenv
)
continue
try:
for tgt in targets:
top[saltenv][tgt] = ctop[saltenv][tgt]
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def _merge_tops_merge_all(self, tops):
'''
Merge the top files into a single dictionary
'''
def _read_tgt(tgt):
match_type = None
states = []
for item in tgt:
if isinstance(item, dict):
match_type = item
if isinstance(item, six.string_types):
states.append(item)
return match_type, states
top = DefaultOrderedDict(OrderedDict)
for ctops in six.itervalues(tops):
for ctop in ctops:
for saltenv, targets in six.iteritems(ctop):
if saltenv == 'include':
continue
try:
for tgt in targets:
if tgt not in top[saltenv]:
top[saltenv][tgt] = ctop[saltenv][tgt]
continue
m_type1, m_states1 = _read_tgt(top[saltenv][tgt])
m_type2, m_states2 = _read_tgt(ctop[saltenv][tgt])
merged = []
match_type = m_type2 or m_type1
if match_type is not None:
merged.append(match_type)
merged.extend(m_states1)
merged.extend([x for x in m_states2 if x not in merged])
top[saltenv][tgt] = merged
except TypeError:
raise SaltRenderError('Unable to render top file. No targets found.')
return top
def verify_tops(self, tops):
'''
Verify the contents of the top file data
'''
errors = []
if not isinstance(tops, dict):
errors.append('Top data was not formed as a dict')
# No further checks will work, bail out
return errors
for saltenv, matches in six.iteritems(tops):
if saltenv == 'include':
continue
if not isinstance(saltenv, six.string_types):
errors.append(
'Environment {0} in top file is not formed as a '
'string'.format(saltenv)
)
if saltenv == '':
errors.append('Empty saltenv statement in top file')
if not isinstance(matches, dict):
errors.append(
'The top file matches for saltenv {0} are not '
'formatted as a dict'.format(saltenv)
)
for slsmods in six.itervalues(matches):
if not isinstance(slsmods, list):
errors.append('Malformed topfile (state declarations not '
'formed as a list)')
continue
for slsmod in slsmods:
if isinstance(slsmod, dict):
# This value is a match option
for val in six.itervalues(slsmod):
if not val:
errors.append(
'Improperly formatted top file matcher '
'in saltenv {0}: {1} file'.format(
slsmod,
val
)
)
elif isinstance(slsmod, six.string_types):
# This is a sls module
if not slsmod:
errors.append(
'Environment {0} contains an empty sls '
'index'.format(saltenv)
)
return errors
def get_top(self):
'''
Returns the high data derived from the top file
'''
try:
tops = self.get_tops()
except SaltRenderError as err:
log.error('Unable to render top file: %s', err.error)
return {}
return self.merge_tops(tops)
def top_matches(self, top):
'''
Search through the top high data for matches and return the states
that this minion needs to execute.
Returns:
{'saltenv': ['state1', 'state2', ...]}
'''
matches = DefaultOrderedDict(OrderedDict)
# pylint: disable=cell-var-from-loop
for saltenv, body in six.iteritems(top):
if self.opts['saltenv']:
if saltenv != self.opts['saltenv']:
continue
for match, data in six.iteritems(body):
def _filter_matches(_match, _data, _opts):
if isinstance(_data, six.string_types):
_data = [_data]
if self.matchers['confirm_top.confirm_top'](
_match,
_data,
_opts
):
if saltenv not in matches:
matches[saltenv] = []
for item in _data:
if 'subfilter' in item:
_tmpdata = item.pop('subfilter')
for match, data in six.iteritems(_tmpdata):
_filter_matches(match, data, _opts)
if isinstance(item, six.string_types):
matches[saltenv].append(item)
elif isinstance(item, dict):
env_key, inc_sls = item.popitem()
if env_key not in self.avail:
continue
if env_key not in matches:
matches[env_key] = []
matches[env_key].append(inc_sls)
_filter_matches(match, data, self.opts['nodegroups'])
ext_matches = self._master_tops()
for saltenv in ext_matches:
top_file_matches = matches.get(saltenv, [])
if self.opts.get('master_tops_first'):
first = ext_matches[saltenv]
second = top_file_matches
else:
first = top_file_matches
second = ext_matches[saltenv]
matches[saltenv] = first + [x for x in second if x not in first]
# pylint: enable=cell-var-from-loop
return matches
def _master_tops(self):
'''
Get results from the master_tops system. Override this function if the
execution of the master_tops needs customization.
'''
return self.client.master_tops()
def load_dynamic(self, matches):
'''
If autoload_dynamic_modules is True then automatically load the
dynamic modules
'''
if not self.opts['autoload_dynamic_modules']:
return
syncd = self.state.functions['saltutil.sync_all'](list(matches),
refresh=False)
if syncd['grains']:
self.opts['grains'] = salt.loader.grains(self.opts)
self.state.opts['pillar'] = self.state._gather_pillar()
self.state.module_refresh()
def render_state(self, sls, saltenv, mods, matches, local=False):
'''
Render a state file and retrieve all of the include states
'''
errors = []
if not local:
state_data = self.client.get_state(sls, saltenv)
fn_ = state_data.get('dest', False)
else:
fn_ = sls
if not os.path.isfile(fn_):
errors.append(
'Specified SLS {0} on local filesystem cannot '
'be found.'.format(sls)
)
state = None
if not fn_:
errors.append(
'Specified SLS {0} in saltenv {1} is not '
'available on the salt master or through a configured '
'fileserver'.format(sls, saltenv)
)
else:
try:
state = compile_template(fn_,
self.state.rend,
self.state.opts['renderer'],
self.state.opts['renderer_blacklist'],
self.state.opts['renderer_whitelist'],
saltenv,
sls,
rendered_sls=mods
)
except SaltRenderError as exc:
msg = 'Rendering SLS \'{0}:{1}\' failed: {2}'.format(
saltenv, sls, exc
)
log.critical(msg)
errors.append(msg)
except Exception as exc:
msg = 'Rendering SLS {0} failed, render error: {1}'.format(
sls, exc
)
log.critical(
msg,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
errors.append('{0}\n{1}'.format(msg, traceback.format_exc()))
try:
mods.add('{0}:{1}'.format(saltenv, sls))
except AttributeError:
pass
if state:
if not isinstance(state, dict):
errors.append(
'SLS {0} does not render to a dictionary'.format(sls)
)
else:
include = []
if 'include' in state:
if not isinstance(state['include'], list):
err = ('Include Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
else:
include = state.pop('include')
self._handle_extend(state, sls, saltenv, errors)
self._handle_exclude(state, sls, saltenv, errors)
self._handle_state_decls(state, sls, saltenv, errors)
for inc_sls in include:
# inc_sls may take the form of:
# 'sls.to.include' <- same as {<saltenv>: 'sls.to.include'}
# {<env_key>: 'sls.to.include'}
# {'_xenv': 'sls.to.resolve'}
xenv_key = '_xenv'
if isinstance(inc_sls, dict):
env_key, inc_sls = inc_sls.popitem()
else:
env_key = saltenv
if env_key not in self.avail:
msg = ('Nonexistent saltenv \'{0}\' found in include '
'of \'{1}\' within SLS \'{2}:{3}\''
.format(env_key, inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
if inc_sls.startswith('.'):
match = re.match(r'^(\.+)(.*)$', inc_sls)
if match:
levels, include = match.groups()
else:
msg = ('Badly formatted include {0} found in include '
'in SLS \'{2}:{3}\''
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
level_count = len(levels)
p_comps = sls.split('.')
if state_data.get('source', '').endswith('/init.sls'):
p_comps.append('init')
if level_count > len(p_comps):
msg = ('Attempted relative include of \'{0}\' '
'within SLS \'{1}:{2}\' '
'goes beyond top level package '
.format(inc_sls, saltenv, sls))
log.error(msg)
errors.append(msg)
continue
inc_sls = '.'.join(p_comps[:-level_count] + [include])
if env_key != xenv_key:
if matches is None:
matches = []
# Resolve inc_sls in the specified environment
if env_key in matches or fnmatch.filter(self.avail[env_key], inc_sls):
resolved_envs = [env_key]
else:
resolved_envs = []
else:
# Resolve inc_sls in the subset of environment matches
resolved_envs = [
aenv for aenv in matches
if fnmatch.filter(self.avail[aenv], inc_sls)
]
# An include must be resolved to a single environment, or
# the include must exist in the current environment
if len(resolved_envs) == 1 or saltenv in resolved_envs:
# Match inc_sls against the available states in the
# resolved env, matching wildcards in the process. If
# there were no matches, then leave inc_sls as the
# target so that the next recursion of render_state
# will recognize the error.
sls_targets = fnmatch.filter(
self.avail[saltenv],
inc_sls
) or [inc_sls]
for sls_target in sls_targets:
r_env = resolved_envs[0] if len(resolved_envs) == 1 else saltenv
mod_tgt = '{0}:{1}'.format(r_env, sls_target)
if mod_tgt not in mods:
nstate, err = self.render_state(
sls_target,
r_env,
mods,
matches
)
if nstate:
self.merge_included_states(state, nstate, errors)
state.update(nstate)
if err:
errors.extend(err)
else:
msg = ''
if not resolved_envs:
msg = ('Unknown include: Specified SLS {0}: {1} is not available on the salt '
'master in saltenv(s): {2} '
).format(env_key,
inc_sls,
', '.join(matches) if env_key == xenv_key else env_key)
elif len(resolved_envs) > 1:
msg = ('Ambiguous include: Specified SLS {0}: {1} is available on the salt master '
'in multiple available saltenvs: {2}'
).format(env_key,
inc_sls,
', '.join(resolved_envs))
log.critical(msg)
errors.append(msg)
try:
self._handle_iorder(state)
except TypeError:
log.critical('Could not render SLS %s. Syntax error detected.', sls)
else:
state = {}
return state, errors
def _handle_iorder(self, state):
'''
Take a state and apply the iorder system
'''
if self.opts['state_auto_order']:
for name in state:
for s_dec in state[name]:
if not isinstance(s_dec, six.string_types):
# PyDSL OrderedDict?
continue
if not isinstance(state[name], dict):
# Include's or excludes as lists?
continue
if not isinstance(state[name][s_dec], list):
# Bad syntax, let the verify seq pick it up later on
continue
found = False
if s_dec.startswith('_'):
continue
for arg in state[name][s_dec]:
if isinstance(arg, dict):
if arg:
if next(six.iterkeys(arg)) == 'order':
found = True
if not found:
if not isinstance(state[name][s_dec], list):
# quite certainly a syntax error, managed elsewhere
continue
state[name][s_dec].append(
{'order': self.iorder}
)
self.iorder += 1
return state
def _handle_state_decls(self, state, sls, saltenv, errors):
'''
Add sls and saltenv components to the state
'''
for name in state:
if not isinstance(state[name], dict):
if name == '__extend__':
continue
if name == '__exclude__':
continue
if isinstance(state[name], six.string_types):
# Is this is a short state, it needs to be padded
if '.' in state[name]:
comps = state[name].split('.')
state[name] = {'__sls__': sls,
'__env__': saltenv,
comps[0]: [comps[1]]}
continue
errors.append(
'ID {0} in SLS {1} is not a dictionary'.format(name, sls)
)
continue
skeys = set()
for key in list(state[name]):
if key.startswith('_'):
continue
if not isinstance(state[name][key], list):
continue
if '.' in key:
comps = key.split('.')
# Salt doesn't support state files such as:
#
# /etc/redis/redis.conf:
# file.managed:
# - source: salt://redis/redis.conf
# - user: redis
# - group: redis
# - mode: 644
# file.comment:
# - regex: ^requirepass
if comps[0] in skeys:
errors.append(
'ID \'{0}\' in SLS \'{1}\' contains multiple state '
'declarations of the same type'.format(name, sls)
)
continue
state[name][comps[0]] = state[name].pop(key)
state[name][comps[0]].append(comps[1])
skeys.add(comps[0])
continue
skeys.add(key)
if '__sls__' not in state[name]:
state[name]['__sls__'] = sls
if '__env__' not in state[name]:
state[name]['__env__'] = saltenv
def _handle_extend(self, state, sls, saltenv, errors):
'''
Take the extend dec out of state and apply to the highstate global
dec
'''
if 'extend' in state:
ext = state.pop('extend')
if not isinstance(ext, dict):
errors.append(('Extension value in SLS \'{0}\' is not a '
'dictionary').format(sls))
return
for name in ext:
if not isinstance(ext[name], dict):
errors.append(('Extension name \'{0}\' in SLS \'{1}\' is '
'not a dictionary'
.format(name, sls)))
continue
if '__sls__' not in ext[name]:
ext[name]['__sls__'] = sls
if '__env__' not in ext[name]:
ext[name]['__env__'] = saltenv
for key in list(ext[name]):
if key.startswith('_'):
continue
if not isinstance(ext[name][key], list):
continue
if '.' in key:
comps = key.split('.')
ext[name][comps[0]] = ext[name].pop(key)
ext[name][comps[0]].append(comps[1])
state.setdefault('__extend__', []).append(ext)
def _handle_exclude(self, state, sls, saltenv, errors):
'''
Take the exclude dec out of the state and apply it to the highstate
global dec
'''
if 'exclude' in state:
exc = state.pop('exclude')
if not isinstance(exc, list):
err = ('Exclude Declaration in SLS {0} is not formed '
'as a list'.format(sls))
errors.append(err)
state.setdefault('__exclude__', []).extend(exc)
def render_highstate(self, matches):
'''
Gather the state files and render them into a single unified salt
high data structure.
'''
highstate = self.building_highstate
all_errors = []
mods = set()
statefiles = []
for saltenv, states in six.iteritems(matches):
for sls_match in states:
if saltenv in self.avail:
statefiles = fnmatch.filter(self.avail[saltenv], sls_match)
elif '__env__' in self.avail:
statefiles = fnmatch.filter(self.avail['__env__'], sls_match)
else:
all_errors.append(
'No matching salt environment for environment '
'\'{0}\' found'.format(saltenv)
)
# if we did not found any sls in the fileserver listing, this
# may be because the sls was generated or added later, we can
# try to directly execute it, and if it fails, anyway it will
# return the former error
if not statefiles:
statefiles = [sls_match]
for sls in statefiles:
r_env = '{0}:{1}'.format(saltenv, sls)
if r_env in mods:
continue
state, errors = self.render_state(
sls, saltenv, mods, matches)
if state:
self.merge_included_states(highstate, state, errors)
for i, error in enumerate(errors[:]):
if 'is not available' in error:
# match SLS foobar in environment
this_sls = 'SLS {0} in saltenv'.format(
sls_match)
if this_sls in error:
errors[i] = (
'No matching sls found for \'{0}\' '
'in env \'{1}\''.format(sls_match, saltenv))
all_errors.extend(errors)
self.clean_duplicate_extends(highstate)
return highstate, all_errors
def clean_duplicate_extends(self, highstate):
if '__extend__' in highstate:
highext = []
for items in (six.iteritems(ext) for ext in highstate['__extend__']):
for item in items:
if item not in highext:
highext.append(item)
highstate['__extend__'] = [{t[0]: t[1]} for t in highext]
def merge_included_states(self, highstate, state, errors):
# The extend members can not be treated as globally unique:
if '__extend__' in state:
highstate.setdefault('__extend__',
[]).extend(state.pop('__extend__'))
if '__exclude__' in state:
highstate.setdefault('__exclude__',
[]).extend(state.pop('__exclude__'))
for id_ in state:
if id_ in highstate:
if highstate[id_] != state[id_]:
errors.append((
'Detected conflicting IDs, SLS'
' IDs need to be globally unique.\n The'
' conflicting ID is \'{0}\' and is found in SLS'
' \'{1}:{2}\' and SLS \'{3}:{4}\'').format(
id_,
highstate[id_]['__env__'],
highstate[id_]['__sls__'],
state[id_]['__env__'],
state[id_]['__sls__'])
)
try:
highstate.update(state)
except ValueError:
errors.append(
'Error when rendering state with contents: {0}'.format(state)
)
def _check_pillar(self, force=False):
'''
Check the pillar for errors, refuse to run the state if there are
errors in the pillar and return the pillar errors
'''
if force:
return True
if '_errors' in self.state.opts['pillar']:
return False
return True
def matches_whitelist(self, matches, whitelist):
'''
Reads over the matches and returns a matches dict with just the ones
that are in the whitelist
'''
if not whitelist:
return matches
ret_matches = {}
if not isinstance(whitelist, list):
whitelist = whitelist.split(',')
for env in matches:
for sls in matches[env]:
if sls in whitelist:
ret_matches[env] = ret_matches[env] if env in ret_matches else []
ret_matches[env].append(sls)
return ret_matches
def call_highstate(self, exclude=None, cache=None, cache_name='highstate',
force=False, whitelist=None, orchestration_jid=None):
'''
Run the sequence to execute the salt highstate for this minion
'''
# Check that top file exists
tag_name = 'no_|-states_|-states_|-None'
ret = {tag_name: {
'result': False,
'comment': 'No states found for this minion',
'name': 'No States',
'changes': {},
'__run_num__': 0,
}}
cfn = os.path.join(
self.opts['cachedir'],
'{0}.cache.p'.format(cache_name)
)
if cache:
if os.path.isfile(cfn):
with salt.utils.files.fopen(cfn, 'rb') as fp_:
high = self.serial.load(fp_)
return self.state.call_high(high, orchestration_jid)
# File exists so continue
err = []
try:
top = self.get_top()
except SaltRenderError as err:
ret[tag_name]['comment'] = 'Unable to render top file: '
ret[tag_name]['comment'] += six.text_type(err.error)
return ret
except Exception:
trb = traceback.format_exc()
err.append(trb)
return err
err += self.verify_tops(top)
matches = self.top_matches(top)
if not matches:
msg = ('No Top file or master_tops data matches found. Please see '
'master log for details.')
ret[tag_name]['comment'] = msg
return ret
matches = self.matches_whitelist(matches, whitelist)
self.load_dynamic(matches)
if not self._check_pillar(force):
err += ['Pillar failed to render with the following messages:']
err += self.state.opts['pillar']['_errors']
else:
high, errors = self.render_highstate(matches)
if exclude:
if isinstance(exclude, six.string_types):
exclude = exclude.split(',')
if '__exclude__' in high:
high['__exclude__'].extend(exclude)
else:
high['__exclude__'] = exclude
err += errors
if err:
return err
if not high:
return ret
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Make sure cache file isn't read-only
self.state.functions['cmd.run'](
['attrib', '-R', cfn],
python_shell=False,
output_loglevel='quiet')
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
self.serial.dump(high, fp_)
except TypeError:
# Can't serialize pydsl
pass
except (IOError, OSError):
log.error('Unable to write to "state.highstate" cache file %s', cfn)
return self.state.call_high(high, orchestration_jid)
def compile_highstate(self):
'''
Return just the highstate or the errors
'''
err = []
top = self.get_top()
err += self.verify_tops(top)
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
err += errors
if err:
return err
return high
def compile_low_chunks(self):
'''
Compile the highstate but don't run it, return the low chunks to
see exactly what the highstate will execute
'''
top = self.get_top()
matches = self.top_matches(top)
high, errors = self.render_highstate(matches)
# If there is extension data reconcile it
high, ext_errors = self.state.reconcile_extend(high)
errors += ext_errors
# Verify that the high data is structurally sound
errors += self.state.verify_high(high)
high, req_in_errors = self.state.requisite_in(high)
errors += req_in_errors
high = self.state.apply_exclude(high)
if errors:
return errors
# Compile and verify the raw chunks
chunks = self.state.compile_high_data(high)
return chunks
|
saltstack/salt
|
salt/state.py
|
MasterState.load_modules
|
python
|
def load_modules(self, data=None, proxy=None):
'''
Load the modules into the state
'''
log.info('Loading fresh modules for state activity')
# Load a modified client interface that looks like the interface used
# from the minion, but uses remote execution
#
self.functions = salt.client.FunctionWrapper(
self.opts,
self.opts['id']
)
# Load the states, but they should not be used in this class apart
# from inspection
self.utils = salt.loader.utils(self.opts)
self.serializers = salt.loader.serializers(self.opts)
self.states = salt.loader.states(self.opts, self.functions, self.utils, self.serializers)
self.rend = salt.loader.render(self.opts, self.functions, states=self.states, context=self.state_con)
|
Load the modules into the state
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/state.py#L4298-L4315
| null |
class MasterState(State):
'''
Create a State object for master side compiling
'''
def __init__(self, opts, minion):
State.__init__(self, opts)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.