desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Run git_pillar with the specified configuration'
def get_pillar(self, ext_pillar_conf):
cachedir = tempfile.mkdtemp(dir=TMP) self.addCleanup(shutil.rmtree, cachedir, ignore_errors=True) ext_pillar_opts = yaml.safe_load(ext_pillar_conf.format(cachedir=cachedir, extmods=os.path.join(cachedir, 'extmods'), **self.ext_opts)) with patch.dict(git_pillar.__opts__, ext_pillar_opts): return ...
'Create the SSH server and user, and create the git repo'
def setUp(self):
super(GitPillarSSHTestBase, self).setUp() self.sshd_proc = self.find_proc(name='sshd', search=self.sshd_config) self.sshd_bin = salt.utils.path.which('sshd') if (self.sshd_proc is None): self.spawn_server() known_hosts_ret = self.run_function('ssh.set_known_host', user=self.master_opts['...
'Wrap the parent class\' get_pillar() func in logic that temporarily changes the GIT_SSH to use our custom script, ensuring that the passphraselsess key is used to auth without needing to modify the root user\'s ssh config file.'
def get_pillar(self, ext_pillar_conf):
orig_git_ssh = os.environ.pop('GIT_SSH', NOTSET) os.environ['GIT_SSH'] = self.git_ssh try: return super(GitPillarSSHTestBase, self).get_pillar(ext_pillar_conf) finally: os.environ.pop('GIT_SSH', None) if (orig_git_ssh is not NOTSET): os.environ['GIT_SSH'] = orig_git_s...
'Create and start the webserver, and create the git repo'
def setUp(self):
super(GitPillarHTTPTestBase, self).setUp() self.nginx_proc = self.find_proc(name='nginx', search=self.nginx_conf) self.uwsgi_proc = self.find_proc(name='uwsgi', search=self.uwsgi_conf) if ((self.nginx_proc is None) and (self.uwsgi_proc is None)): self.spawn_server() self.make_repo(self.repo_...
'Validate the default available options'
def _validate_options(self):
if ((self.xml_output_dir is not None) and self.options.xml_out and (HAS_XMLRUNNER is False)): self.error("'--xml' is not available. The xmlrunner library is not installed.") if self.options.xml_out: self.xml_output_dir = self.options.xml_out if ((self.xml_output_di...
'Setup python\'s logging system to work with/for the tests suite'
def _setup_logging(self):
formatter = logging.Formatter('%(asctime)s,%(msecs)03.0f [%(name)-5s:%(lineno)-4d][%(levelname)-8s] %(message)s', datefmt='%H:%M:%S') if (not hasattr(logging, 'TRACE')): logging.TRACE = 5 logging.addLevelName(logging.TRACE, 'TRACE') if (not hasattr(logging, 'GARBAGE')): logging...
'Run any initial clean up operations. If sub-classed, don\'t forget to call SaltTestingParser.pre_execution_cleanup(self) from the overridden method.'
def pre_execution_cleanup(self):
if (self.options.clean is True): for path in (self.xml_output_dir,): if (path is None): continue if os.path.isdir(path): shutil.rmtree(path)
'Execute a unit test suite'
def run_suite(self, path, display_name, suffix='test_*.py', load_from_name=False, additional_test_dirs=None):
loaded_custom = False loader = TestLoader() try: if load_from_name: tests = loader.loadTestsFromName(display_name) elif ((additional_test_dirs is None) or self.testsuite_directory.startswith(path)): tests = loader.discover(path, suffix, self.testsuite_directory) ...
'Print a nicely formatted report about the test suite results'
def print_overall_testsuite_report(self):
print() print_header(u' Overall Tests Report ', sep=u'=', centered=True, inline=True, width=self.options.output_columns) failures = errors = skipped = passed = 0 no_problems_found = True for results in self.testsuite_results: failures += len(results.failures) erro...
'Run the finalization procedures. Show report, clean-up file-system, etc'
def finalize(self, exit_code=0):
children = helpers.collect_child_processes(os.getpid()) if (self.options.no_report is False): self.print_overall_testsuite_report() self.post_execution_cleanup() if children: log.info('Terminating test suite child processes: %s', children) helpers.terminate_process...
'Run the tests suite in a Docker container'
def run_suite_in_docker(self):
def stop_running_docked_container(cid, signum=None, frame=None): time.sleep(0.5) print_header('', inline=True, width=self.options.output_columns) scode_call = subprocess.Popen([self.options.docker_binary, 'inspect', '--format={{.State.Running}}', cid], env=os.environ.copy(), close_fds=True, ...
'Run one or more ``unittest.case.TestCase``'
def run_testcase(self, testcase):
header = '' loader = TestLoader() if isinstance(testcase, list): for case in testcase: tests = loader.loadTestsFromTestCase(case) else: tests = loader.loadTestsFromTestCase(testcase) if (not isinstance(testcase, list)): header = '{0} Tests'.format(testcase.__na...
'Start code coverage. You can pass any coverage options as keyword arguments. For the available options please see: http://nedbatchelder.com/code/coverage/api.html'
def start_coverage(self, **coverage_options):
if (self.options.coverage is False): return if (coverage_options.pop('track_processes', None) is not None): raise RuntimeWarning("Please stop passing 'track_processes' to 'start_coverage()'. It's now the default and '--no-processes-coverage' was added to...
'Stop code coverage.'
def stop_coverage(self, save_coverage=True):
if (self.options.coverage is False): return os.environ.pop('COVERAGE_OPTIONS', None) os.environ.pop('COVERAGE_PROCESS_START', None) print(' * Stopping coverage') self.code_coverage.stop() if save_coverage: print(' * Saving coverage info') self.code_co...
'root Root directory of webserver. If not passed, it will default to the location of the base environment of the integration suite\'s file roots (tests/integration/files/file/base/) port Port on which to listen. If not passed, a random one will be chosen at the time the start() function is invoked. wait : 5 Number of s...
def __init__(self, root=None, port=None, wait=5, handler=None):
if ((port is not None) and (not isinstance(port, six.integer_types))): raise ValueError('port must be an integer') if (root is None): root = os.path.join(FILES, 'file', 'base') try: self.root = os.path.realpath(root) except AttributeError: raise ValueError('ro...
'Threading target which stands up the tornado application'
def target(self):
self.ioloop = tornado.ioloop.IOLoop() self.ioloop.make_current() self.application = tornado.web.Application([('/(.*)', self.handler, {'path': self.root})]) self.application.listen(self.port) self.ioloop.start()
'Convenience function which, given a file path, will return a URL that points to that path. If the path is relative, it will just be appended to self.web_root.'
def url(self, path):
if (self.web_root is None): raise RuntimeError('Webserver instance has not been started') err_msg = 'invalid path, must be either a relative path or a path within {0}'.format(self.root) try: relpath = (path if (not os.path.isabs(path)) else ...
'Starts the webserver'
def start(self):
if (self.port is None): self.port = get_unused_localhost_port() self.web_root = 'http://127.0.0.1:{0}'.format(self.port) self.server_thread = threading.Thread(target=self.target) self.server_thread.daemon = True self.server_thread.start() for idx in range((self.wait + 1)): if sel...
'Stops the webserver'
def stop(self):
self.ioloop.add_callback(self.ioloop.stop) self.server_thread.join()
'Return the path to a testing runtime script'
def get_script_path(self, script_name):
if (not os.path.isdir(TMP_SCRIPT_DIR)): os.makedirs(TMP_SCRIPT_DIR) script_path = os.path.join(TMP_SCRIPT_DIR, 'cli_{0}.py'.format(script_name.replace('-', '_'))) if (not os.path.isfile(script_path)): log.info('Generating {0}'.format(script_path)) import salt.utils.files w...
'CherryPy does not have a facility for serverless unit testing. However this recipe demonstrates a way of doing it by calling its internal API to simulate an incoming request. This will exercise the whole stack from there. Remember a couple of things: * CherryPy is multithreaded. The response you will get from this met...
def request(self, path='/', method='GET', app_path='', scheme='http', proto='HTTP/1.1', body=None, qs=None, headers=None, **kwargs):
h = {'Host': '127.0.0.1'} fd = None if (body is not None): h['content-length'] = '{0}'.format(len(body)) fd = StringIO(body) if (headers is not None): h.update(headers) app = cherrypy.tree.apps.get(app_path) if (not app): raise AssertionError("No application ...
'Return a set of all test suites except unit and cloud provider tests unless requested'
def _get_suites(self, include_unit=False, include_cloud_provider=False, include_proxy=False):
suites = set(TEST_SUITES.keys()) if (not include_unit): suites -= set(['unit']) if (not include_cloud_provider): suites -= set(['cloud_provider']) if (not include_proxy): suites -= set(['proxy']) return suites
'Query whether test suites have been enabled'
def _check_enabled_suites(self, include_unit=False, include_cloud_provider=False, include_proxy=False):
suites = self._get_suites(include_unit=include_unit, include_cloud_provider=include_cloud_provider, include_proxy=include_proxy) return any([getattr(self.options, suite) for suite in suites])
'Enable test suites for current test run'
def _enable_suites(self, include_unit=False, include_cloud_provider=False, include_proxy=False):
suites = self._get_suites(include_unit=include_unit, include_cloud_provider=include_cloud_provider, include_proxy=include_proxy) for suite in suites: setattr(self.options, suite, True)
'Run an integration test suite'
def run_integration_suite(self, path='', display_name=''):
full_path = os.path.join(TEST_DIR, path) return self.run_suite(full_path, display_name, suffix='test_*.py')
'Set soft and hard limits on open file handles at required thresholds for integration tests or unit tests'
def set_filehandle_limits(self, limits='integration'):
if salt.utils.platform.is_windows(): import win32file prev_hard = win32file._getmaxstdio() prev_soft = 512 else: (prev_soft, prev_hard) = resource.getrlimit(resource.RLIMIT_NOFILE) min_soft = MAX_OPEN_FILES[limits]['soft_limit'] min_hard = MAX_OPEN_FILES[limits]['hard_lim...
'Execute the integration tests suite'
def run_integration_tests(self):
named_tests = [] named_unit_test = [] if self.options.name: for test in self.options.name: if test.startswith(('tests.unit.', 'unit.')): named_unit_test.append(test) continue named_tests.append(test) if ((self.options.unit or named_unit_tes...
'Execute the unit tests'
def run_unit_tests(self):
named_unit_test = [] if self.options.name: for test in self.options.name: if (not test.startswith(('tests.unit.', 'unit.'))): continue named_unit_test.append(test) if ((not self.options.unit) and (not named_unit_test)): return [True] status = [] ...
'Simulate writing data Args: data: Returns:'
def write(self, data):
self.content.append(data)
'Simulate closing the IO object. Returns:'
def close(self):
self.closed = True
'Fill in the blanks for the eauth system'
def __eauth(self):
if self.opts['eauth']: resolver = salt.auth.Resolver(self.opts) res = resolver.cli(self.opts['eauth']) self.opts.update(res)
'Execute the wheel call'
def run(self):
return self.wheel.master_call(**self.opts)
'Ensure exception does not display a context by default Wraps TestCase.assertRaisesRegex'
@contextlib.contextmanager def assertCleanError(self, exc_type, details, *args):
if args: details = (details % args) cm = self.assertRaisesRegex(exc_type, details) with cm as exc: (yield exc)
'Ensure a clean AddressValueError'
def assertAddressError(self, details, *args):
return self.assertCleanError(ipaddress.AddressValueError, details, *args)
'Ensure a clean NetmaskValueError'
def assertNetmaskError(self, details, *args):
return self.assertCleanError(ipaddress.NetmaskValueError, details, *args)
'Check constructor arguments produce equivalent instances'
def assertInstancesEqual(self, lhs, rhs):
self.assertEqual(self.factory(lhs), self.factory(rhs))
'Ensure a clean ValueError with the expected message'
def assertFactoryError(self, factory, kind):
addr = 'camelot' msg = '%r does not appear to be an IPv4 or IPv6 %s' with self.assertCleanError(ValueError, msg, addr, kind): factory(addr)
'Run the sequence in a loop'
def run(self):
last_check = 0 self.start_time = datetime.datetime.now() goal = (self.reqs_sec * self.run_time) while True: self.fire_it() last_check += 1 if (last_check > self.granularity): self.calibrate() last_check = 0 if (self.total_complete > goal): ...
'Send the pub!'
def fire_it(self):
self.client.pub('silver', 'test.ping') self.total_complete += 1
'Re-calibrate the speed'
def calibrate(self):
elapsed_time = (datetime.datetime.now() - self.start_time) runtime_reqs_sec = (self.total_complete / elapsed_time.total_seconds()) print('Recalibrating. Current reqs/sec: {0}'.format(runtime_reqs_sec)) return
'Read a file on the file system (relative to salt\'s base project dir) :returns: A file-like object. :raises IOError: If the file cannot be found or read.'
def parse_file(self, fpath):
sdir = os.path.abspath(os.path.join(os.path.dirname(salt.__file__), os.pardir)) with open(os.path.join(sdir, fpath), 'rb') as f: return f.readlines()
'Parse a string line-by-line delineating comments and code :returns: An tuple of boolean/list-of-string pairs. True designates a comment; False designates code.'
def parse_lit(self, lines):
comment_char = '#' comment = re.compile('^\\s*{0}[ \\n]'.format(comment_char)) section_test = (lambda val: bool(comment.match(val))) sections = [] for (is_doc, group) in itertools.groupby(lines, section_test): if is_doc: text = [comment.sub('', i).rstrip('\r\n') for i in group...
'Given a typical Salt SLS path (e.g.: apache.vhosts.standard), find the file on the file system and parse it'
def parse_file(self, sls_path):
config = self.state.document.settings.env.config formulas_dirs = config.formulas_dirs fpath = sls_path.replace('.', '/') name_options = ('{0}.sls'.format(fpath), os.path.join(fpath, 'init.sls')) paths = [os.path.join(fdir, fname) for fname in name_options for fdir in formulas_dirs] for i in path...
'Stores the specified attributes which represent a URL which links to an RFC which defines an HTTP method.'
def __init__(self, base_url, anchor, section):
self.base_url = base_url self.anchor = anchor self.section = section
'Returns the URL which this object represents, which points to the location of the RFC which defines some HTTP method.'
def __repr__(self):
return '{0}#{1}{2}'.format(self.base_url, self.anchor, self.section)
'Format the function name'
def format_name(self):
if (not hasattr(self.module, '__func_alias__')): return super(FunctionDocumenter, self).format_name() if (not self.objpath): return super(FunctionDocumenter, self).format_name() if (len(self.objpath) > 1): return super(FunctionDocumenter, self).format_name() return self.module.__...
'Mapping allows autodoc to bypass the Mock object, but actually assign a specific value, expected by a specific attribute returned.'
def __init__(self, mapping=None, *args, **kwargs):
self.__mapping = (mapping or {})
'Provide access eg. to \'pack\''
def __getattr__(self, attr):
return getattr(self.client.functions, attr)
'Return a function that you can call with regular func params, but will do all the _proc_function magic'
def __getitem__(self, key):
if (key not in self.client.functions): raise KeyError def wrapper(*args, **kwargs): low = {u'fun': key, u'args': args, u'kwargs': kwargs} pub_data = {} kwargs_keys = list(kwargs) for kwargs_key in kwargs_keys: if kwargs_key.startswith(u'__pub_'): ...
'Return a dict that will mimic the "functions" dict used all over salt. It creates a wrapper around the function allowing **kwargs, and if pub_data is passed in as kwargs, will re-use the JID passed in'
def functions_dict(self):
return ClientFuncsDict(self)
'Execute a function through the master network interface.'
def master_call(self, **kwargs):
load = kwargs load[u'cmd'] = self.client channel = salt.transport.Channel.factory(self.opts, crypt=u'clear', usage=u'master_call') ret = channel.send(load) if isinstance(ret, collections.Mapping): if (u'error' in ret): salt.utils.error.raise_error(**ret[u'error']) return ret
'Execute a runner function synchronously; eauth is respected This function requires that :conf_master:`external_auth` is configured and the user is authorized to execute runner functions: (``@runner``). .. code-block:: python runner.eauth_sync({ \'fun\': \'jobs.list_jobs\', \'username\': \'saltdev\', \'password\': \'sa...
def cmd_sync(self, low, timeout=None, full_return=False):
event = salt.utils.event.get_master_event(self.opts, self.opts[u'sock_dir'], listen=True) job = self.master_call(**low) ret_tag = salt.utils.event.tagify(u'ret', base=job[u'tag']) if (timeout is None): timeout = self.opts.get(u'rest_timeout', 300) ret = event.get_event(tag=ret_tag, full=True...
'Execute a function .. code-block:: python >>> opts = salt.config.master_config(\'/etc/salt/master\') >>> runner = salt.runner.RunnerClient(opts) >>> runner.cmd(\'jobs.list_jobs\', []) \'20131219215650131543\': { \'Arguments\': [300], \'Function\': \'test.sleep\', \'StartTime\': \'2013, Dec 19 21:56:50.131543\', \'Targ...
def cmd(self, fun, arg=None, pub_data=None, kwarg=None, print_event=True, full_return=False):
if (arg is None): arg = tuple() if ((not isinstance(arg, list)) and (not isinstance(arg, tuple))): raise salt.exceptions.SaltInvocationError(u'arg must be formatted as a list/tuple') if (pub_data is None): pub_data = {} if (not isinstance(pub_data, dict)): ...
'Check for deprecated usage and allow until Salt Oxygen.'
def low(self, fun, low, print_event=True, full_return=False):
msg = [] if (u'args' in low): msg.append(u'call with arg instead') low[u'arg'] = low.pop(u'args') if (u'kwargs' in low): msg.append(u'call with kwarg instead') low[u'kwarg'] = low.pop(u'kwargs') if msg: salt.utils.warn_until(u'Oxygen', u' '.jo...
'Helper that allows us to turn off storing jobs for different classes that may incorporate this mixin.'
@property def store_job(self):
try: class_name = self.__class__.__name__.lower() except AttributeError: log.warning(u'Unable to determine class name', exc_info_on_loglevel=logging.DEBUG) return True try: return self.opts[u'{0}_returns'.format(class_name)] except KeyError: return Tru...
'Execute a function from low data Low data includes: required: - fun: the name of the function to run optional: - arg: a list of args to pass to fun - kwarg: kwargs for fun - __user__: user who is running the command - __jid__: jid to run under - __tag__: tag to run under'
def _low(self, fun, low, print_event=True, full_return=False):
self.mminion jid = low.get(u'__jid__', salt.utils.jid.gen_jid()) tag = low.get(u'__tag__', salt.utils.event.tagify(jid, prefix=self.tag_prefix)) data = {u'fun': u'{0}.{1}'.format(self.client, fun), u'jid': jid, u'user': low.get(u'__user__', u'UNKNOWN')} event = salt.utils.event.get_event(u'master', ...
'Return a dictionary of functions and the inline documentation for each'
def get_docs(self, arg=None):
if arg: if (u'*' in arg): target_mod = arg _use_fnmatch = True else: target_mod = ((arg + u'.') if (not arg.endswith(u'.')) else arg) if _use_fnmatch: docs = [(fun, self.functions[fun].__doc__) for fun in fnmatch.filter(self.functions, target_m...
'Run this method in a multiprocess target to execute the function in a multiprocess and fire the return data on the event bus'
def _proc_function(self, fun, low, user, tag, jid, daemonize=True):
if (daemonize and (not salt.utils.platform.is_windows())): salt.log.setup.shutdown_multiprocessing_logging() salt.utils.daemonize() salt.log.setup.setup_multiprocessing_logging() low[u'__jid__'] = jid low[u'__user__'] = user low[u'__tag__'] = tag return self.low(fun, low, ful...
'Execute a function asynchronously; eauth is respected This function requires that :conf_master:`external_auth` is configured and the user is authorized .. code-block:: python >>> wheel.cmd_async({ \'fun\': \'key.finger\', \'match\': \'jerry\', \'eauth\': \'auto\', \'username\': \'saltdev\', \'password\': \'saltdev\', ...
def cmd_async(self, low):
return self.master_call(**low)
'Execute the function in a multiprocess and return the event tag to use to watch for the return'
def async(self, fun, low, user=u'UNKNOWN', pub=None):
async_pub = (pub if (pub is not None) else self._gen_async_pub()) proc = salt.utils.process.SignalHandlingMultiprocessingProcess(target=self._proc_function, args=(fun, low, user, async_pub[u'tag'], async_pub[u'jid'])) with salt.utils.process.default_signals(signal.SIGINT, signal.SIGTERM): proc.start...
'Print all of the events with the prefix \'tag\''
def print_async_event(self, suffix, event):
if (not isinstance(event, dict)): return if self.opts.get(u'quiet', False): return if (suffix in (u'new',)): return try: outputter = self.opts.get(u'output', (event.get(u'outputter', None) or event.get(u'return').get(u'outputter'))) except AttributeError: outp...
':param IOLoop io_loop: io_loop used for events. Pass in an io_loop if you want asynchronous operation for obtaining events. Eg use of set_event_handler() API. Otherwise, operation will be synchronous.'
def __init__(self, c_path=os.path.join(syspaths.CONFIG_DIR, u'master'), mopts=None, skip_perm_errors=False, io_loop=None, keep_loop=False, auto_reconnect=False):
if mopts: self.opts = mopts else: if os.path.isdir(c_path): log.warning(u"%s expects a file path not a directory path(%s) to its 'c_path' keyword argument", self.__class__.__name__, c_path) self.opts = salt.config.client_config(c_path) ...
'Read in the rotating master authentication key'
def __read_master_key(self):
key_user = self.salt_user if (key_user == u'root'): if (self.opts.get(u'user', u'root') != u'root'): key_user = self.opts.get(u'user', u'root') if key_user.startswith(u'sudo_'): key_user = self.opts.get(u'user', u'root') if salt.utils.platform.is_windows(): key_user =...
'convert a seco.range range into a list target'
def _convert_range_to_list(self, tgt):
range_ = seco.range.Range(self.opts[u'range_server']) try: return range_.expand(tgt) except seco.range.RangeException as err: print(u'Range server exception: {0}'.format(err)) return []
'Return the timeout to use'
def _get_timeout(self, timeout):
if (timeout is None): return self.opts[u'timeout'] if isinstance(timeout, int): return timeout if isinstance(timeout, six.string_types): try: return int(timeout) except ValueError: return self.opts[u'timeout'] return self.opts[u'timeout']
'Return the information about a given job'
def gather_job_info(self, jid, tgt, tgt_type, **kwargs):
log.debug(u'Checking whether jid %s is still running', jid) timeout = int(kwargs.get(u'gather_job_timeout', self.opts[u'gather_job_timeout'])) pub_data = self.run_job(tgt, u'saltutil.find_job', arg=[jid], tgt_type=tgt_type, timeout=timeout, **kwargs) if (u'jid' in pub_data): se...
'Common checks on the pub_data data structure returned from running pub'
def _check_pub_data(self, pub_data):
if (pub_data == u''): raise EauthAuthenticationError(u'Failed to authenticate! This is most likely because this user is not permitted to execute commands, but there is a small possibility that a disk error occurred (check di...
'Asynchronously send a command to connected minions Prep the job directory and publish a command to any targeted minions. :return: A dictionary of (validated) ``pub_data`` or an empty dictionary on failure. The ``pub_data`` contains the job ID and a list of all minions that are expected to return data. .. code-block:: ...
def run_job(self, tgt, fun, arg=(), tgt_type=u'glob', ret=u'', timeout=None, jid=u'', kwarg=None, listen=False, **kwargs):
if (u'expr_form' in kwargs): salt.utils.warn_until(u'Fluorine', u"The target type should be passed using the 'tgt_type' argument instead of 'expr_form'. Support for using 'expr_form' will be removed in Salt Fluorine.") tgt_type = kwar...
'Asynchronously send a command to connected minions Prep the job directory and publish a command to any targeted minions. :return: A dictionary of (validated) ``pub_data`` or an empty dictionary on failure. The ``pub_data`` contains the job ID and a list of all minions that are expected to return data. .. code-block:: ...
@tornado.gen.coroutine def run_job_async(self, tgt, fun, arg=(), tgt_type=u'glob', ret=u'', timeout=None, jid=u'', kwarg=None, listen=True, io_loop=None, **kwargs):
if (u'expr_form' in kwargs): salt.utils.warn_until(u'Fluorine', u"The target type should be passed using the 'tgt_type' argument instead of 'expr_form'. Support for using 'expr_form' will be removed in Salt Fluorine.") tgt_type = kwar...
'Asynchronously send a command to connected minions The function signature is the same as :py:meth:`cmd` with the following exceptions. :returns: A job ID or 0 on failure. .. code-block:: python >>> local.cmd_async(\'*\', \'test.sleep\', [300]) \'20131219215921857715\''
def cmd_async(self, tgt, fun, arg=(), tgt_type=u'glob', ret=u'', jid=u'', kwarg=None, **kwargs):
if (u'expr_form' in kwargs): salt.utils.warn_until(u'Fluorine', u"The target type should be passed using the 'tgt_type' argument instead of 'expr_form'. Support for using 'expr_form' will be removed in Salt Fluorine.") tgt_type = kwar...
'Execute a command on a random subset of the targeted systems The function signature is the same as :py:meth:`cmd` with the following exceptions. :param sub: The number of systems to execute on .. code-block:: python >>> SLC.cmd_subset(\'*\', \'test.ping\', sub=1) {\'jerry\': True}'
def cmd_subset(self, tgt, fun, arg=(), tgt_type=u'glob', ret=u'', kwarg=None, sub=3, cli=False, progress=False, **kwargs):
if (u'expr_form' in kwargs): salt.utils.warn_until(u'Fluorine', u"The target type should be passed using the 'tgt_type' argument instead of 'expr_form'. Support for using 'expr_form' will be removed in Salt Fluorine.") tgt_type = kwar...
'Iteratively execute a command on subsets of minions at a time The function signature is the same as :py:meth:`cmd` with the following exceptions. :param batch: The batch identifier of systems to execute on :returns: A generator of minion returns .. code-block:: python >>> returns = local.cmd_batch(\'*\', \'state.highs...
def cmd_batch(self, tgt, fun, arg=(), tgt_type=u'glob', ret=u'', kwarg=None, batch=u'10%', **kwargs):
if (u'expr_form' in kwargs): salt.utils.warn_until(u'Fluorine', u"The target type should be passed using the 'tgt_type' argument instead of 'expr_form'. Support for using 'expr_form' will be removed in Salt Fluorine.") tgt_type = kwar...
'Synchronously execute a command on targeted minions The cmd method will execute and wait for the timeout period for all minions to reply, then it will return all minion data at once. .. code-block:: python >>> import salt.client >>> local = salt.client.LocalClient() >>> local.cmd(\'*\', \'cmd.run\', [\'whoami\']) {\'j...
def cmd(self, tgt, fun, arg=(), timeout=None, tgt_type=u'glob', ret=u'', jid=u'', full_return=False, kwarg=None, **kwargs):
if (u'expr_form' in kwargs): salt.utils.warn_until(u'Fluorine', u"The target type should be passed using the 'tgt_type' argument instead of 'expr_form'. Support for using 'expr_form' will be removed in Salt Fluorine.") tgt_type = kwar...
'Used by the :command:`salt` CLI. This method returns minion returns as they come back and attempts to block until all minions return. The function signature is the same as :py:meth:`cmd` with the following exceptions. :param verbose: Print extra information about the running command :returns: A generator'
def cmd_cli(self, tgt, fun, arg=(), timeout=None, tgt_type=u'glob', ret=u'', verbose=False, kwarg=None, progress=False, **kwargs):
if (u'expr_form' in kwargs): salt.utils.warn_until(u'Fluorine', u"The target type should be passed using the 'tgt_type' argument instead of 'expr_form'. Support for using 'expr_form' will be removed in Salt Fluorine.") tgt_type = kwar...
'Yields the individual minion returns as they come in The function signature is the same as :py:meth:`cmd` with the following exceptions. :return: A generator yielding the individual minion returns .. code-block:: python >>> ret = local.cmd_iter(\'*\', \'test.ping\') >>> for i in ret: ... print(i) {\'jerry\': {\'re...
def cmd_iter(self, tgt, fun, arg=(), timeout=None, tgt_type=u'glob', ret=u'', kwarg=None, **kwargs):
if (u'expr_form' in kwargs): salt.utils.warn_until(u'Fluorine', u"The target type should be passed using the 'tgt_type' argument instead of 'expr_form'. Support for using 'expr_form' will be removed in Salt Fluorine.") tgt_type = kwar...
'Yields the individual minion returns as they come in, or None when no returns are available. The function signature is the same as :py:meth:`cmd` with the following exceptions. :returns: A generator yielding the individual minion returns, or None when no returns are available. This allows for actions to be injected in...
def cmd_iter_no_block(self, tgt, fun, arg=(), timeout=None, tgt_type=u'glob', ret=u'', kwarg=None, show_jid=False, verbose=False, **kwargs):
if (u'expr_form' in kwargs): salt.utils.warn_until(u'Fluorine', u"The target type should be passed using the 'tgt_type' argument instead of 'expr_form'. Support for using 'expr_form' will be removed in Salt Fluorine.") tgt_type = kwar...
'Execute a salt command and return'
def cmd_full_return(self, tgt, fun, arg=(), timeout=None, tgt_type=u'glob', ret=u'', verbose=False, kwarg=None, **kwargs):
if (u'expr_form' in kwargs): salt.utils.warn_until(u'Fluorine', u"The target type should be passed using the 'tgt_type' argument instead of 'expr_form'. Support for using 'expr_form' will be removed in Salt Fluorine.") tgt_type = kwar...
'Starts a watcher looking at the return data for a specified JID :returns: all of the information for the JID'
def get_cli_returns(self, jid, minions, timeout=None, tgt=u'*', tgt_type=u'glob', verbose=False, show_jid=False, **kwargs):
if (u'expr_form' in kwargs): salt.utils.warn_until(u'Fluorine', u"The target type should be passed using the 'tgt_type' argument instead of 'expr_form'. Support for using 'expr_form' will be removed in Salt Fluorine.") tgt_type = kwar...
'Raw function to just return events of jid excluding timeout logic Yield either the raw event data or None Pass a list of additional regular expressions as `tags_regex` to search the event bus for non-return data, such as minion lists returned from syndics.'
def get_returns_no_block(self, tag, match_type=None):
while True: raw = self.event.get_event(wait=0.01, tag=tag, match_type=match_type, full=True, no_block=True, auto_reconnect=self.auto_reconnect) (yield raw)
'Watch the event system and return job data as it comes in :returns: all of the information for the JID'
def get_iter_returns(self, jid, minions, timeout=None, tgt=u'*', tgt_type=u'glob', expect_minions=False, block=True, **kwargs):
if (u'expr_form' in kwargs): salt.utils.warn_until(u'Fluorine', u"The target type should be passed using the 'tgt_type' argument instead of 'expr_form'. Support for using 'expr_form' will be removed in Salt Fluorine.") tgt_type = kwar...
'Get the returns for the command line interface via the event system'
def get_returns(self, jid, minions, timeout=None):
minions = set(minions) if (timeout is None): timeout = self.opts[u'timeout'] start = int(time.time()) timeout_at = (start + timeout) log.debug(u'get_returns for jid %s sent to %s will timeout at %s', jid, minions, datetime.fromtimestamp(timeout_at).time()) f...
'This method starts off a watcher looking at the return data for a specified jid, it returns all of the information for the jid'
def get_full_returns(self, jid, minions, timeout=None):
ret = {} event_iter = self.get_event_iter_returns(jid, minions, timeout=timeout) try: data = self.returners[u'{0}.get_jid'.format(self.opts[u'master_job_cache'])](jid) except Exception as exc: raise SaltClientError(u'Returner {0} could not fetch jid data. Exception ...
'Execute a single pass to gather the contents of the job cache'
def get_cache_returns(self, jid):
ret = {} try: data = self.returners[u'{0}.get_jid'.format(self.opts[u'master_job_cache'])](jid) except Exception as exc: raise SaltClientError(u'Could not examine master job cache. Error occurred in {0} returner. Exception details: {1}'.format(self.opts...
'Get the returns for the command line interface via the event system'
def get_cli_static_event_returns(self, jid, minions, timeout=None, tgt=u'*', tgt_type=u'glob', verbose=False, show_timeout=False, show_jid=False):
log.trace(u'entered - function get_cli_static_event_returns()') minions = set(minions) if verbose: msg = u'Executing job with jid {0}'.format(jid) print(msg) print(((u'-' * len(msg)) + u'\n')) elif show_jid: print(u'jid: {0}'.format(jid)) if (t...
'Get the returns for the command line interface via the event system'
def get_cli_event_returns(self, jid, minions, timeout=None, tgt=u'*', tgt_type=u'glob', verbose=False, progress=False, show_timeout=False, show_jid=False, **kwargs):
log.trace(u'func get_cli_event_returns()') if (u'expr_form' in kwargs): salt.utils.warn_until(u'Fluorine', u"The target type should be passed using the 'tgt_type' argument instead of 'expr_form'. Support for using 'expr_form' will be removed ...
'Gather the return data from the event system, break hard when timeout is reached.'
def get_event_iter_returns(self, jid, minions, timeout=None):
log.trace(u'entered - function get_event_iter_returns()') if (timeout is None): timeout = self.opts[u'timeout'] timeout_at = (time.time() + timeout) found = set() if (self.returners[u'{0}.get_load'.format(self.opts[u'master_job_cache'])](jid) == {}): log.warning(u'jid doe...
'Set up the payload_kwargs to be sent down to the master'
def _prep_pub(self, tgt, fun, arg, tgt_type, ret, jid, timeout, **kwargs):
if (tgt_type == u'nodegroup'): if (tgt not in self.opts[u'nodegroups']): conf_file = self.opts.get(u'conf_file', u'the master config file') raise SaltInvocationError(u'Node group {0} unavailable in {1}'.format(tgt, conf_file)) tgt = salt.utils.minions....
'Take the required arguments and publish the given command. Arguments: tgt: The tgt is a regex or a glob used to match up the ids on the minions. Salt works by always publishing every command to all of the minions and then the minions determine if the command is for them based on the tgt value. fun: The function name t...
def pub(self, tgt, fun, arg=(), tgt_type=u'glob', ret=u'', jid=u'', timeout=5, listen=False, **kwargs):
if (u'expr_form' in kwargs): salt.utils.warn_until(u'Fluorine', u"The target type should be passed using the 'tgt_type' argument instead of 'expr_form'. Support for using 'expr_form' will be removed in Salt Fluorine.") tgt_type = kwar...
'Take the required arguments and publish the given command. Arguments: tgt: The tgt is a regex or a glob used to match up the ids on the minions. Salt works by always publishing every command to all of the minions and then the minions determine if the command is for them based on the tgt value. fun: The function name t...
@tornado.gen.coroutine def pub_async(self, tgt, fun, arg=(), tgt_type=u'glob', ret=u'', jid=u'', timeout=5, io_loop=None, listen=True, **kwargs):
if (u'expr_form' in kwargs): salt.utils.warn_until(u'Fluorine', u"The target type should be passed using the 'tgt_type' argument instead of 'expr_form'. Support for using 'expr_form' will be removed in Salt Fluorine.") tgt_type = kwar...
'Since the function key is missing, wrap this call to a command to the minion of said key if it is available in the self.functions set'
def __missing__(self, key):
if (key not in self.functions): raise KeyError return self.run_key(key)
'Find out what functions are available on the minion'
def __load_functions(self):
return set(self.local.cmd(self.minion, u'sys.list_functions').get(self.minion, []))
'Return a function that executes the arguments passed via the local client'
def run_key(self, key):
def func(*args, **kwargs): '\n Run a remote call\n ' args = list(args) for (_key, _val) in kwargs: args.append(u'{0}={1}'.format(_key, _val)) return self.local.cmd(self....
'Call an execution module with the given arguments and keyword arguments .. versionchanged:: 2015.8.0 Added the ``cmd`` method for consistency with the other Salt clients. The existing ``function`` and ``sminion.functions`` interfaces still exist but have been removed from the docs. .. code-block:: python caller.cmd(\'...
def cmd(self, fun, *args, **kwargs):
return self.sminion.functions[fun](*args, **kwargs)
'Call a single salt function'
def function(self, fun, *args, **kwargs):
func = self.sminion.functions[fun] (args, kwargs) = salt.minion.load_args_and_kwargs(func, salt.utils.args.parse_input(args), kwargs) return func(*args, **kwargs)
'Load and start all available api modules'
def run(self):
if (not len(self.netapi)): log.error(u'Did not find any netapi configurations, nothing to start') for fun in self.netapi: if fun.endswith(u'.start'): log.info(u'Starting %s netapi module', fun) self.process_manager.add_process(self.netapi[...
'Publish the command!'
def pub(self, tgt, fun, arg=(), tgt_type=u'glob', ret=u'', jid=u'', timeout=5, **kwargs):
if (u'expr_form' in kwargs): salt.utils.warn_until(u'Fluorine', u"The target type should be passed using the 'tgt_type' argument instead of 'expr_form'. Support for using 'expr_form' will be removed in Salt Fluorine.") tgt_type = kwar...
'Execute the salt command given by cmd dict. cmd is a dictionary of the following form: \'mode\': \'modestring\', \'fun\' : \'modulefunctionstring\', \'kwarg\': functionkeywordargdictionary, \'tgt\' : \'targetpatternstring\', \'tgt_type\' : \'targetpatterntype\', \'ret\' : \'returner namestring\', \'timeout\': \'functi...
def run(self, cmd):
cmd = dict(cmd) client = u'minion' mode = cmd.get(u'mode', u'async') funparts = cmd.get(u'fun', u'').split(u'.') if ((len(funparts) > 2) and (funparts[0] in [u'wheel', u'runner'])): client = funparts[0] cmd[u'fun'] = u'.'.join(funparts[1:]) if (not ((u'token' in cmd) or ((u'eauth...
'Wrap LocalClient for running :ref:`execution modules <all-salt.modules>` and immediately return the job ID. The results of the job can then be retrieved at a later time. .. seealso:: :ref:`python-api`'
def minion_async(self, **kwargs):
return self.localClient.run_job(**kwargs)
'Wrap LocalClient for running :ref:`execution modules <all-salt.modules>` .. seealso:: :ref:`python-api`'
def minion_sync(self, **kwargs):
return self.localClient.cmd(**kwargs)
'Wrap RunnerClient for executing :ref:`runner modules <all-salt.runners>` Expects that one of the kwargs is key \'fun\' whose value is the namestring of the function to call'
def runner_async(self, **kwargs):
return self.runnerClient.master_call(**kwargs)