desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'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 th...
def _merge_tops_merge(self, tops):
top = DefaultOrderedDict(OrderedDict) base_tops = tops.pop(u'base', DefaultOrderedDict(OrderedDict)) for ctop in base_tops: for (saltenv, targets) in six.iteritems(ctop): if (saltenv == u'include'): continue try: for tgt in targets: ...
'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.'
def _merge_tops_same(self, tops):
top = DefaultOrderedDict(OrderedDict) for (cenv, ctops) in six.iteritems(tops): if all([(x == {}) for x in ctops]): default_top = self.opts[u'default_top'] fallback_tops = tops.get(default_top, []) if all([(x == {}) for x in fallback_tops]): log.error(...
'Merge the top files into a single dictionary'
def _merge_tops_merge_all(self, tops):
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(...
'Verify the contents of the top file data'
def verify_tops(self, tops):
errors = [] if (not isinstance(tops, dict)): errors.append(u'Top data was not formed as a dict') return errors for (saltenv, matches) in six.iteritems(tops): if (saltenv == u'include'): continue if (not isinstance(saltenv, six.string_types)): ...
'Returns the high data derived from the top file'
def get_top(self):
try: tops = self.get_tops() except SaltRenderError as err: log.error((u'Unable to render top file: ' + str(err.error))) return {} return self.merge_tops(tops)
'Search through the top high data for matches and return the states that this minion needs to execute. Returns: {\'saltenv\': [\'state1\', \'state2\', ...]}'
def top_matches(self, top):
matches = {} for (saltenv, body) in six.iteritems(top): if self.opts[u'environment']: if (saltenv != self.opts[u'environment']): continue for (match, data) in six.iteritems(body): def _filter_matches(_match, _data, _opts): if isinstance(_da...
'Get results from the master_tops system. Override this function if the execution of the master_tops needs customization.'
def _master_tops(self):
return self.client.master_tops()
'If autoload_dynamic_modules is True then automatically load the dynamic modules'
def load_dynamic(self, matches):
if (not self.opts[u'autoload_dynamic_modules']): return syncd = self.state.functions[u'saltutil.sync_all'](list(matches), refresh=False) if syncd[u'grains']: self.opts[u'grains'] = salt.loader.grains(self.opts) self.state.opts[u'pillar'] = self.state._gather_pillar() self.state.m...
'Render a state file and retrieve all of the include states'
def render_state(self, sls, saltenv, mods, matches, local=False):
errors = [] if (not local): state_data = self.client.get_state(sls, saltenv) fn_ = state_data.get(u'dest', False) else: fn_ = sls if (not os.path.isfile(fn_)): errors.append(u'Specified SLS {0} on local filesystem cannot be found.'.format(s...
'Take a state and apply the iorder system'
def _handle_iorder(self, state):
if self.opts[u'state_auto_order']: for name in state: for s_dec in state[name]: if (not isinstance(s_dec, six.string_types)): continue if (not isinstance(state[name], dict)): continue if (not isinstance(state...
'Add sls and saltenv components to the state'
def _handle_state_decls(self, state, sls, saltenv, errors):
for name in state: if (not isinstance(state[name], dict)): if (name == u'__extend__'): continue if (name == u'__exclude__'): continue if isinstance(state[name], six.string_types): if (u'.' in state[name]): ...
'Take the extend dec out of state and apply to the highstate global dec'
def _handle_extend(self, state, sls, saltenv, errors):
if (u'extend' in state): ext = state.pop(u'extend') if (not isinstance(ext, dict)): errors.append(u"Extension value in SLS '{0}' is not a dictionary".format(sls)) return for name in ext: if (not isinstance(ext[name], dict)): ...
'Take the exclude dec out of the state and apply it to the highstate global dec'
def _handle_exclude(self, state, sls, saltenv, errors):
if (u'exclude' in state): exc = state.pop(u'exclude') if (not isinstance(exc, list)): err = u'Exclude Declaration in SLS {0} is not formed as a list'.format(sls) errors.append(err) state.setdefault(u'__exclude__', []).extend(exc)
'Gather the state files and render them into a single unified salt high data structure.'
def render_highstate(self, matches):
highstate = self.building_highstate all_errors = [] mods = set() statefiles = [] for (saltenv, states) in six.iteritems(matches): for sls_match in states: try: statefiles = fnmatch.filter(self.avail[saltenv], sls_match) except KeyError: ...
'Check the pillar for errors, refuse to run the state if there are errors in the pillar and return the pillar errors'
def _check_pillar(self, force=False):
if force: return True if (u'_errors' in self.state.opts[u'pillar']): return False return True
'Reads over the matches and returns a matches dict with just the ones that are in the whitelist'
def matches_whitelist(self, matches, whitelist):
if (not whitelist): return matches ret_matches = {} if (not isinstance(whitelist, list)): whitelist = whitelist.split(u',') for env in matches: for sls in matches[env]: if (sls in whitelist): ret_matches[env] = (ret_matches[env] if (env in ret_matches)...
'Run the sequence to execute the salt highstate for this minion'
def call_highstate(self, exclude=None, cache=None, cache_name=u'highstate', force=False, whitelist=None, orchestration_jid=None):
tag_name = u'no_|-states_|-states_|-None' ret = {tag_name: {u'result': False, u'comment': u'No states found for this minion', u'name': u'No States', u'changes': {}, u'__run_num__': 0}} cfn = os.path.join(self.opts[u'cachedir'], u'{0}.cache.p'.format(cache_name)) if cache: if os...
'Return just the highstate or the errors'
def compile_highstate(self):
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
'Compile the highstate but don\'t run it, return the low chunks to see exactly what the highstate will execute'
def compile_low_chunks(self):
top = self.get_top() matches = self.top_matches(top) (high, errors) = self.render_highstate(matches) (high, ext_errors) = self.state.reconcile_extend(high) errors += ext_errors errors += self.state.verify_high(high) (high, req_in_errors) = self.state.requisite_in(high) errors += req_in_e...
'Return all used and unused states for the minion based on the top match data'
def compile_state_usage(self):
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 = {u'used': [], u'unused': [], u'count_all': 0, u'count_used': 0, u'count_unused': 0} ...
'Load the modules into the state'
def load_modules(self, data=None, proxy=None):
log.info(u'Loading fresh modules for state activity') self.functions = salt.client.FunctionWrapper(self.opts, self.opts[u'id']) self.utils = salt.loader.utils(self.opts) self.serializers = salt.loader.serializers(self.opts) self.states = salt.loader.states(self.opts, self.functions, s...
'Return the state data from the master'
def compile_master(self):
load = {u'grains': self.grains, u'opts': self.opts, u'cmd': u'_master_state'} try: return self.channel.send(load, tries=3, timeout=72000) except SaltReqTimeoutError: return {}
'Run the SPM command'
def run(self, args):
command = args[0] try: if (command == 'install'): self._install(args) elif (command == 'local'): self._local(args) elif (command == 'repo'): self._repo(args) elif (command == 'remove'): self._remove(args) elif (command == 'b...
'Process local commands'
def _list(self, args):
args.pop(0) command = args[0] if (command == 'packages'): self._list_packages(args) elif (command == 'files'): self._list_files(args) elif (command == 'repos'): self._repo_list(args) else: raise SPMInvocationError("Invalid list command '{0}'".format(comma...
'Process local commands'
def _local(self, args):
args.pop(0) command = args[0] if (command == 'install'): self._local_install(args) elif (command == 'files'): self._local_list_files(args) elif (command == 'info'): self._local_info(args) else: raise SPMInvocationError("Invalid local command '{0}'".format...
'Process repo commands'
def _repo(self, args):
args.pop(0) command = args[0] if (command == 'list'): self._repo_list(args) elif (command == 'packages'): self._repo_packages(args) elif (command == 'search'): self._repo_packages(args, search=True) elif (command == 'update'): self._download_repo_metadata(args) ...
'List packages for one or more configured repos'
def _repo_packages(self, args, search=False):
packages = [] repo_metadata = self._get_repo_metadata() for repo in repo_metadata: for pkg in repo_metadata[repo]['packages']: if (args[1] in pkg): version = repo_metadata[repo]['packages'][pkg]['info']['version'] release = repo_metadata[repo]['packages'][...
'List configured repos This can be called either as a ``repo`` command or a ``list`` command'
def _repo_list(self, args):
repo_metadata = self._get_repo_metadata() for repo in repo_metadata: self.ui.status(repo)
'Install a package from a repo'
def _install(self, args):
if (len(args) < 2): raise SPMInvocationError('A package must be specified') caller_opts = self.opts.copy() caller_opts['file_client'] = 'local' self.caller = salt.client.Caller(mopts=caller_opts) self.client = salt.client.get_local_client(self.opts['conf_file']) cache = salt....
'Install a package from a file'
def _local_install(self, args, pkg_name=None):
if (len(args) < 2): raise SPMInvocationError('A package file must be specified') self._install(args)
'Starting with one package, check all packages for dependencies'
def _check_all_deps(self, pkg_name=None, pkg_file=None, formula_def=None):
if (pkg_file and (not os.path.exists(pkg_file))): raise SPMInvocationError('Package file {0} not found'.format(pkg_file)) self.repo_metadata = self._get_repo_metadata() if (not formula_def): for repo in self.repo_metadata: if (not isinstance(self.repo_metadata[repo]['...
'Install one individual package'
def _install_indv_pkg(self, pkg_name, pkg_file):
self.ui.status('... installing {0}'.format(pkg_name)) formula_tar = tarfile.open(pkg_file, 'r:bz2') formula_ref = formula_tar.extractfile('{0}/FORMULA'.format(pkg_name)) formula_def = yaml.safe_load(formula_ref) for field in ('version', 'release', 'summary', 'description'): if (field n...
'Return a list of packages which need to be installed, to resolve all dependencies'
def _resolve_deps(self, formula_def):
pkg_info = self.pkgdb['{0}.info'.format(self.db_prov)](formula_def['name']) if (not isinstance(pkg_info, dict)): pkg_info = {} can_has = {} cant_has = [] if (('dependencies' in formula_def) and (formula_def['dependencies'] is None)): formula_def['dependencies'] = '' for dep in fo...
'Traverse through all repo files and apply the functionality provided in the callback to them'
def _traverse_repos(self, callback, repo_name=None):
repo_files = [] if os.path.exists(self.opts['spm_repos_config']): repo_files.append(self.opts['spm_repos_config']) for (dirpath, dirnames, filenames) in os.walk('{0}.d'.format(self.opts['spm_repos_config'])): for repo_file in filenames: if (not repo_file.endswith('.repo')): ...
'Download files via http'
def _query_http(self, dl_path, repo_info):
query = None response = None try: if ('username' in repo_info): try: if ('password' in repo_info): query = http.query(dl_path, text=True, username=repo_info['username'], password=repo_info['password']) else: raise SP...
'Connect to all repos and download metadata'
def _download_repo_metadata(self, args):
cache = salt.cache.Cache(self.opts, self.opts['spm_cache_dir']) def _update_metadata(repo, repo_info): dl_path = '{0}/SPM-METADATA'.format(repo_info['url']) if dl_path.startswith('file://'): dl_path = dl_path.replace('file://', '') with salt.utils.files.fopen(dl_path, 'r'...
'Return cached repo metadata'
def _get_repo_metadata(self):
cache = salt.cache.Cache(self.opts, self.opts['spm_cache_dir']) metadata = {} def _read_metadata(repo, repo_info): if (cache.updated('.', repo) is None): log.warn('Updating repo metadata') self._download_repo_metadata({}) metadata[repo] = {'info': repo_info, 'pa...
'Scan a directory and create an SPM-METADATA file which describes all of the SPM files in that directory.'
def _create_repo(self, args):
if (len(args) < 2): raise SPMInvocationError('A path to a directory must be specified') if (args[1] == '.'): repo_path = os.environ['PWD'] else: repo_path = args[1] old_files = [] repo_metadata = {} for (dirpath, dirnames, filenames) in os.walk(repo_p...
'Remove a package'
def _remove(self, args):
if (len(args) < 2): raise SPMInvocationError('A package must be specified') packages = args[1:] msg = 'Removing packages:\n DCTB {0}'.format('\n DCTB '.join(packages)) if (not self.opts['assume_yes']): self.ui.confirm(msg) for package in packages: self.ui.statu...
'Display verbose information'
def _verbose(self, msg, level=log.debug):
if (self.opts.get('verbose', False) is True): self.ui.status(msg) level(msg)
'List info for a package file'
def _local_info(self, args):
if (len(args) < 2): raise SPMInvocationError('A package filename must be specified') pkg_file = args[1] if (not os.path.exists(pkg_file)): raise SPMInvocationError('Package file {0} not found'.format(pkg_file)) comps = pkg_file.split('-') comps = '-'.join(c...
'List info for a package'
def _info(self, args):
if (len(args) < 2): raise SPMInvocationError('A package must be specified') package = args[1] pkg_info = self._pkgdb_fun('info', package, self.db_conn) if (pkg_info is None): raise SPMPackageError('package {0} not installed'.format(package)) self.ui.status(self._...
'Get package info'
def _get_info(self, formula_def):
fields = ('name', 'os', 'os_family', 'release', 'version', 'dependencies', 'os_dependencies', 'os_family_dependencies', 'summary', 'description') for item in fields: if (item not in formula_def): formula_def[item] = 'None' if ('installed' not in formula_def): formula_def['install...
'List files for a package file'
def _local_list_files(self, args):
if (len(args) < 2): raise SPMInvocationError('A package filename must be specified') pkg_file = args[1] if (not os.path.exists(pkg_file)): raise SPMPackageError('Package file {0} not found'.format(pkg_file)) formula_tar = tarfile.open(pkg_file, 'r:bz2') pkg...
'List files for an installed package'
def _list_packages(self, args):
packages = self._pkgdb_fun('list_packages', self.db_conn) for package in packages: if self.opts['verbose']: status_msg = ','.join(package) else: status_msg = package[0] self.ui.status(status_msg)
'List files for an installed package'
def _list_files(self, args):
if (len(args) < 2): raise SPMInvocationError('A package name must be specified') package = args[(-1)] files = self._pkgdb_fun('list_files', package, self.db_conn) if (files is None): raise SPMPackageError('package {0} not installed'.format(package)) else: ...
'Build a package'
def _build(self, args):
if (len(args) < 2): raise SPMInvocationError('A path to a formula must be specified') self.abspath = args[1].rstrip('/') comps = self.abspath.split('/') self.relpath = comps[(-1)] formula_path = '{0}/FORMULA'.format(self.abspath) if (not os.path.exists(formula_path))...
'Exclude based on opts'
def _exclude(self, member):
if isinstance(member, string_types): return None for item in self.opts['spm_build_exclude']: if member.name.startswith('{0}/{1}'.format(self.formula_conf['name'], item)): return None elif member.name.startswith('{0}/{1}'.format(self.abspath, item)): return None ...
'Render a [pre|post]_local_state or [pre|post]_tgt_state script'
def _render(self, data, formula_def):
renderer = formula_def.get('renderer', self.opts.get('renderer', 'yaml_jinja')) rend = salt.loader.render(self.opts, {}) blacklist = self.opts.get('renderer_blacklist') whitelist = self.opts.get('renderer_whitelist') template_vars = formula_def.copy() template_vars['opts'] = self.opts.copy() ...
'Report an SPMClient status message'
def status(self, msg):
raise NotImplementedError()
'Report an SPM error message'
def error(self, msg):
raise NotImplementedError()
'Get confirmation from the user before performing an SPMClient action. Return if the action is confirmed, or raise SPMOperationCanceled(<msg>) if canceled.'
def confirm(self, action):
raise NotImplementedError()
'Process the configured beacons The config must be a list and looks like this in yaml .. code_block:: yaml beacons: inotify: - /etc/fstab: {} - /var/cache/foo: {}'
def process(self, config, grains):
ret = [] b_config = copy.deepcopy(config) if (('enabled' in b_config) and (not b_config['enabled'])): return for mod in config: if (mod == 'enabled'): continue current_beacon_config = None if isinstance(config[mod], list): current_beacon_config = {...
'Take a beacon configuration and strip out the interval bits'
def _trim_config(self, b_config, mod, key):
if isinstance(b_config[mod], list): self._remove_list_item(b_config[mod], key) elif isinstance(b_config[mod], dict): b_config[mod].pop(key) return b_config
'Process a beacon configuration to determine its interval'
def _determine_beacon_config(self, current_beacon_config, key):
interval = False if isinstance(current_beacon_config, dict): interval = current_beacon_config.get(key, False) return interval
'Process beacons with intervals Return True if a beacon should be run on this loop'
def _process_interval(self, mod, interval):
log.trace('Processing interval {0} for beacon mod {1}'.format(interval, mod)) loop_interval = self.opts['loop_interval'] if (mod in self.interval_map): log.trace('Processing interval in map') counter = self.interval_map[mod] log.trace('Interval counter: ...
'Return the index of a labeled config item in the beacon config, -1 if the index is not found'
def _get_index(self, beacon_config, label):
indexes = [index for (index, item) in enumerate(beacon_config) if (label in item)] if (len(indexes) < 1): return (-1) else: return indexes[0]
'Remove an item from a beacon config list'
def _remove_list_item(self, beacon_config, label):
index = self._get_index(beacon_config, label) del beacon_config[index]
'Update whether an individual beacon is enabled'
def _update_enabled(self, name, enabled_value):
if isinstance(self.opts['beacons'][name], dict): self.opts['beacons'][name]['enabled'] = enabled_value else: enabled_index = self._get_index(self.opts['beacons'][name], 'enabled') if (enabled_index >= 0): self.opts['beacons'][name][enabled_index]['enabled'] = enabled_value ...
'List the beacon items'
def list_beacons(self):
evt = salt.utils.event.get_event('minion', opts=self.opts) b_conf = self.functions['config.merge']('beacons') self.opts['beacons'].update(b_conf) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_list_complete') return True
'Add a beacon item'
def add_beacon(self, name, beacon_data):
data = {} data[name] = beacon_data if (name in self.opts['beacons']): log.info('Updating settings for beacon item: {0}'.format(name)) else: log.info('Added new beacon item {0}'.format(name)) self.opts['beacons'].update(data) evt = salt.utils.event.get_e...
'Modify a beacon item'
def modify_beacon(self, name, beacon_data):
data = {} data[name] = beacon_data log.info('Updating settings for beacon item: {0}'.format(name)) self.opts['beacons'].update(data) evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/min...
'Delete a beacon item'
def delete_beacon(self, name):
if (name in self.opts['beacons']): log.info('Deleting beacon item {0}'.format(name)) del self.opts['beacons'][name] evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_delete_c...
'Enable beacons'
def enable_beacons(self):
self.opts['beacons']['enabled'] = True evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_enabled_complete') return True
'Enable beacons'
def disable_beacons(self):
self.opts['beacons']['enabled'] = False evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacons_disabled_complete') return True
'Enable a beacon'
def enable_beacon(self, name):
self._update_enabled(name, True) evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_enabled_complete') return True
'Disable a beacon'
def disable_beacon(self, name):
self._update_enabled(name, False) evt = salt.utils.event.get_event('minion', opts=self.opts) evt.fire_event({'complete': True, 'beacons': self.opts['beacons']}, tag='/salt/minion/minion_beacon_disabled_complete') return True
'Connect to F5'
def _connect(self):
try: self.bigIP = f5.BIGIP(hostname=self.lb, username=self.username, password=self.password, fromurl=True, wsdls=['LocalLB.VirtualServer', 'LocalLB.Pool']) except Exception: raise Exception('Unable to connect to {0}'.format(self.lb)) return True
'Create a virtual server'
def create_vs(self, name, ip, port, protocol, profile, pool_name):
vs = self.bigIP.LocalLB.VirtualServer vs_def = vs.typefactory.create('Common.VirtualServerDefinition') vs_def.name = name vs_def.address = ip vs_def.port = port common_protocols = vs.typefactory.create('Common.ProtocolType') p = [i[0] for i in common_protocols if (i[0].split('_')[1] == proto...
'Create a pool on the F5 load balancer'
def create_pool(self, name, method='ROUND_ROBIN'):
lbmethods = self.bigIP.LocalLB.Pool.typefactory.create('LocalLB.LBMethod') supported_method = [i[0] for i in lbmethods if (i[0].split('_', 2)[(-1)] == method.upper())] if (supported_method and (not self.check_pool(name))): try: self.bigIP.LocalLB.Pool.create(pool_names=[name], lb_methods...
'Add a node to a pool'
def add_pool_member(self, name, port, pool_name):
if (not self.check_pool(pool_name)): raise CommandExecutionError('{0} pool does not exists'.format(pool_name)) members_seq = self.bigIP.LocalLB.Pool.typefactory.create('Common.IPPortDefinitionSequence') members_seq.items = [] member = self.bigIP.LocalLB.Pool.typefactory.create('Commo...
'Check to see if a pool exists'
def check_pool(self, name):
pools = self.bigIP.LocalLB.Pool for pool in pools.get_list(): if (pool.split('/')[(-1)] == name): return True return False
'Check to see if a virtual server exists'
def check_virtualserver(self, name):
vs = self.bigIP.LocalLB.VirtualServer for v in vs.get_list(): if (v.split('/')[(-1)] == name): return True return False
'Check a pool member exists in a specific pool'
def check_member_pool(self, member, pool_name):
members = self.bigIP.LocalLB.Pool.get_member(pool_names=[pool_name])[0] for mem in members: if (member == mem.address): return True return False
'List all the load balancer methods'
def lbmethods(self):
methods = self.bigIP.LocalLB.Pool.typefactory.create('LocalLB.LBMethod') return [method[0].split('_', 2)[(-1)] for method in methods]
'Format the log record to include exc_info if the handler is enabled for a specific log level'
def format(self, record):
formatted_record = super(ExcInfoOnLogLevelFormatMixIn, self).format(record) exc_info_on_loglevel = getattr(record, 'exc_info_on_loglevel', None) exc_info_on_loglevel_formatted = getattr(record, 'exc_info_on_loglevel_formatted', None) if ((exc_info_on_loglevel is None) and (exc_info_on_loglevel_formatted...
'Sync the stored log records to the provided log handlers.'
def sync_with_handlers(self, handlers=()):
if (not handlers): return while self.__messages: record = self.__messages.pop(0) for handler in handlers: if (handler.level > record.levelno): continue handler.handle(record)
'Override the default error handling mechanism Deal with log file rotation errors due to log file in use more softly.'
def handleError(self, record):
handled = False if (sys.platform.startswith('win') and logging.raiseExceptions and sys.stderr): (exc_type, exc, exc_traceback) = sys.exc_info() try: if ((exc_type.__name__ in ('PermissionError', 'OSError')) and (exc.winerror == 32)): if (self.level <= logging.WARNING)...
'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__)'
def __new__(cls, *args):
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...
'Set up the process executor'
def __init__(self, opts, fun, config, funcs, runners, proxy, log_queue=None):
super(Engine, self).__init__(log_queue=log_queue) self.opts = opts self.config = config self.fun = fun self.funcs = funcs self.runners = runners self.proxy = proxy
'Run the master service!'
def run(self):
self.utils = salt.loader.utils(self.opts, proxy=self.proxy) if salt.utils.platform.is_windows(): if (self.opts['__role'] == 'master'): self.runners = salt.loader.runner(self.opts, utils=self.utils) else: self.runners = [] self.funcs = salt.loader.minion_mods(self....
'This function will parse the raw syslog data, dynamically create the topic according to the topic specified by the user (if specified) and decide whether to send the syslog data as an event on the master bus, based on the constraints given by the user. :param data: The raw syslog event data which is to be parsed. :par...
def parseData(self, data, host, port, options):
data = self.obj.parse(data) data['hostip'] = host log.debug('Junos Syslog - received {0} from {1}, sent from port {2}'.format(data, host, port)) send_this_event = True for key in options: if (key in data): ...
'This function identifies whether the engine is running on the master or the minion and sends the data to the master event bus accordingly. :param result: It\'s a dictionary which has the final data and topic.'
def send_event_to_salt(self, result):
if result['send']: data = result['data'] topic = result['topic'] if (__opts__['__role'] == 'master'): event.get_master_event(__opts__, __opts__['sock_dir']).fire_event(data, topic) else: __salt__['event.fire_master'](data=data, tag=topic)
'Log the error messages.'
def handle_error(self, err_msg):
log.error(err_msg.getErrorMessage)
'Build the SLSMap'
def construct_yaml_omap(self, node):
sls_map = SLSMap() if (not isinstance(node, MappingNode)): raise ConstructorError(None, None, 'expected a mapping node, but found {0}'.format(node.id), node.start_mark) self.flatten_mapping(node) for (key_node, value_node) in node.value: reset = (key_node.tag == u'!rese...
'Build the SLSString.'
def construct_sls_str(self, node):
obj = self.construct_scalar(node) if six.PY2: obj = obj.encode('utf-8') return SLSString(obj)
'Verify integers and pass them in correctly is they are declared as octal'
def construct_sls_int(self, node):
if (node.value == '0'): pass elif (node.value.startswith('0') and (not node.value.startswith(('0b', '0x')))): node.value = node.value.lstrip('0') if (node.value == ''): node.value = '0' return int(node.value)
'Check cache for the data. If it is there, check to see if it needs to be refreshed. If the data is not there, or it needs to be refreshed, then call the callback function (``fun``) with any given ``**kwargs``. In some cases, the callback function returns a list of objects which need to be processed by a second functio...
def cache(self, bank, key, fun, loop_fun=None, **kwargs):
expire_seconds = kwargs.get('expire', 86400) updated = self.updated(bank, key) update_cache = False if (updated is None): update_cache = True elif ((int(time.time()) - updated) > expire_seconds): update_cache = True data = self.fetch(bank, key) if ((not data) or (update_cache...
'Store data using the specified module :param bank: The name of the location inside the cache which will hold the key and its associated data. :param key: The name of the key (or file inside a directory) which will hold the data. File extensions should not be provided, as they will be added by the driver itself. :param...
def store(self, bank, key, data):
fun = '{0}.store'.format(self.driver) return self.modules[fun](bank, key, data, **self._kwargs)
'Fetch data using the specified module :param bank: The name of the location inside the cache which will hold the key and its associated data. :param key: The name of the key (or file inside a directory) which will hold the data. File extensions should not be provided, as they will be added by the driver itself. :retur...
def fetch(self, bank, key):
fun = '{0}.fetch'.format(self.driver) return self.modules[fun](bank, key, **self._kwargs)
'Get the last updated epoch for the specified key :param bank: The name of the location inside the cache which will hold the key and its associated data. :param key: The name of the key (or file inside a directory) which will hold the data. File extensions should not be provided, as they will be added by the driver its...
def updated(self, bank, key):
fun = '{0}.updated'.format(self.driver) return self.modules[fun](bank, key, **self._kwargs)
'Remove the key from the cache bank with all the key content. If no key is specified remove the entire bank with all keys and sub-banks inside. :param bank: The name of the location inside the cache which will hold the key and its associated data. :param key: The name of the key (or file inside a directory) which will ...
def flush(self, bank, key=None):
fun = '{0}.flush'.format(self.driver) return self.modules[fun](bank, key=key, **self._kwargs)
'Lists entries stored in the specified bank. :param bank: The name of the location inside the cache which will hold the key and its associated data. :return: An iterable object containing all bank entries. Returns an empty iterator if the bank doesn\'t exists. :raises SaltCacheError: Raises an exception if cache driver...
def ls(self, bank):
fun = '{0}.ls'.format(self.driver) return self.modules[fun](bank, **self._kwargs)
'Checks if the specified bank contains the specified key. :param bank: The name of the location inside the cache which will hold the key and its associated data. :param key: The name of the key (or file inside a directory) which will hold the data. File extensions should not be provided, as they will be added by the dr...
def contains(self, bank, key=None):
fun = '{0}.contains'.format(self.driver) return self.modules[fun](bank, key, **self._kwargs)
'Make sure that this path is intended for the salt master and trim it'
def _check_proto(self, path):
if (not path.startswith(u'salt://')): raise MinionError(u'Unsupported path: {0}'.format(path)) (file_path, saltenv) = salt.utils.url.parse(path) return file_path
'Helper util to return a list of files in a directory'
def _file_local_list(self, dest):
if os.path.isdir(dest): destdir = dest else: destdir = os.path.dirname(dest) filelist = set() for (root, dirs, files) in os.walk(destdir, followlinks=True): for name in files: path = os.path.join(root, name) filelist.add(path) return filelist
'Return the local location to cache the file, cache dirs will be made'
@contextlib.contextmanager def _cache_loc(self, path, saltenv=u'base', cachedir=None):
cachedir = self.get_cachedir(cachedir) dest = salt.utils.path.join(cachedir, u'files', saltenv, path) destdir = os.path.dirname(dest) cumask = os.umask(63) if os.path.isfile(destdir): os.remove(destdir) try: os.makedirs(destdir) except OSError as exc: if (exc.errno !=...
'Copies a file from the local files or master depending on implementation'
def get_file(self, path, dest=u'', makedirs=False, saltenv=u'base', gzip=None, cachedir=None):
raise NotImplementedError
'List the empty dirs'
def file_list_emptydirs(self, saltenv=u'base', prefix=u''):
raise NotImplementedError
'Pull a file down from the file server and store it in the minion file cache'
def cache_file(self, path, saltenv=u'base', cachedir=None):
return self.get_url(path, u'', True, saltenv, cachedir=cachedir)