desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Wrap Wheel to enable executing :ref:`wheel modules <all-salt.wheel>` Expects that one of the kwargs is key \'fun\' whose value is the namestring of the function to call'
def wheel_sync(self, **kwargs):
return self.wheelClient.master_call(**kwargs)
'Convenience function that returns dict of function signature(s) specified by cmd. cmd is dict of the form: \'module\' : \'modulestring\', \'tgt\' : \'targetpatternstring\', \'tgt_type\' : \'targetpatterntype\', \'token\': \'salttokenstring\', \'username\': \'usernamestring\', \'password\': \'passwordstring\', \'eauth\...
def signature(self, cmd):
cmd[u'client'] = u'minion' if ((len(cmd[u'module'].split(u'.')) > 2) and (cmd[u'module'].split(u'.')[0] in [u'runner', u'wheel'])): cmd[u'client'] = u'master' return self._signature(cmd)
'Expects everything that signature does and also a client type string. client can either be master or minion.'
def _signature(self, cmd):
result = {} client = cmd.get(u'client', u'minion') if (client == u'minion'): cmd[u'fun'] = u'sys.argspec' cmd[u'kwarg'] = dict(module=cmd[u'module']) result = self.run(cmd) elif (client == u'master'): parts = cmd[u'module'].split(u'.') client = parts[0] mo...
'Create token with creds. Token authorizes salt access if successful authentication with the credentials in creds. creds format is as follows: \'username\': \'namestring\', \'password\': \'passwordstring\', \'eauth\': \'eauthtypestring\', examples of valid eauth type strings: \'pam\' or \'ldap\' Returns dictionary of t...
def create_token(self, creds):
try: tokenage = self.resolver.mk_token(creds) except Exception as ex: raise EauthAuthenticationError(u'Authentication failed with {0}.'.format(repr(ex))) if (u'token' not in tokenage): raise EauthAuthenticationError(u'Authentication failed with provided credentia...
'If token is valid Then returns user name associated with token Else False.'
def verify_token(self, token):
try: result = self.resolver.get_token(token) except Exception as ex: raise EauthAuthenticationError(u'Token validation failed with {0}.'.format(repr(ex))) return result
'Get a single salt event. If no events are available, then block for up to ``wait`` seconds. Return the event if it matches the tag (or ``tag`` is empty) Otherwise return None If wait is 0 then block forever or until next event becomes available.'
def get_event(self, wait=0.25, tag=u'', full=False):
return self.event.get_event(wait=wait, tag=tag, full=full, auto_reconnect=True)
'fires event with data and tag This only works if api is running with same user permissions as master Need to convert this to a master call with appropriate authentication'
def fire_event(self, data, tag):
return self.event.fire_event(data, tagify(tag, u'wui'))
'Return the key string for the SSH public key'
def get_pubkey(self):
if ((u'__master_opts__' in self.opts) and self.opts[u'__master_opts__'].get(u'ssh_use_home_key') and os.path.isfile(os.path.expanduser(u'~/.ssh/id_rsa'))): priv = os.path.expanduser(u'~/.ssh/id_rsa') else: priv = self.opts.get(u'ssh_priv', os.path.join(self.opts[u'pki_dir'], u'ssh', u'salt-ssh.r...
'Deploy the SSH key if the minions don\'t auth'
def key_deploy(self, host, ret):
if ((not isinstance(ret[host], dict)) or self.opts.get(u'ssh_key_deploy')): target = self.targets[host] if (target.get(u'passwd', False) or self.opts[u'ssh_passwd']): self._key_deploy_run(host, target, False) return ret if ret[host].get(u'stderr', u'').count(u'Permission d...
'The ssh-copy-id routine'
def _key_deploy_run(self, host, target, re_run=True):
argv = [u'ssh.set_auth_key', target.get(u'user', u'root'), self.get_pubkey()] single = Single(self.opts, argv, host, mods=self.mods, fsclient=self.fsclient, thin=self.thin, **target) if salt.utils.path.which(u'ssh-copy-id'): (stdout, stderr, retcode) = single.shell.copy_id() else: (stdou...
'Run the routine in a "Thread", put a dict on the queue'
def handle_routine(self, que, opts, host, target, mine=False):
opts = copy.deepcopy(opts) single = Single(opts, opts[u'argv'], host, mods=self.mods, fsclient=self.fsclient, thin=self.thin, mine=mine, **target) ret = {u'id': single.id} (stdout, stderr, retcode) = single.run() try: data = salt.utils.find_json(stdout) if ((len(data) < 2) and (u'loc...
'Spin up the needed threads or processes and execute the subsequent routines'
def handle_ssh(self, mine=False):
que = multiprocessing.Queue() running = {} target_iter = self.targets.__iter__() returned = set() rets = set() init = False while True: if (not self.targets): log.error(u'No matching targets found in roster.') break if ((len(running) < s...
'Execute and yield returns as they come in, do not print to the display mine The Single objects will use mine_functions defined in the roster, pillar, or master config (they will be checked in that order) and will modify the argv with the arguments from mine_functions'
def run_iter(self, mine=False, jid=None):
fstr = u'{0}.prep_jid'.format(self.opts[u'master_job_cache']) jid = self.returners[fstr](passed_jid=(jid or self.opts.get(u'jid', None))) argv = self.opts[u'argv'] if self.opts.get(u'raw_shell', False): fun = u'ssh._raw' args = argv else: fun = (argv[0] if argv else u'') ...
'Cache the job information'
def cache_job(self, jid, id_, ret, fun):
self.returners[u'{0}.returner'.format(self.opts[u'master_job_cache'])]({u'jid': jid, u'id': id_, u'return': ret, u'fun': fun})
'Execute the overall routine, print results via outputters'
def run(self, jid=None):
fstr = u'{0}.prep_jid'.format(self.opts[u'master_job_cache']) jid = self.returners[fstr](passed_jid=(jid or self.opts.get(u'jid', None))) argv = self.opts[u'argv'] if self.opts.get(u'raw_shell', False): fun = u'ssh._raw' args = argv else: fun = (argv[0] if argv else u'') ...
'Return the function name and the arg list'
def __arg_comps(self):
fun = (self.argv[0] if self.argv else u'') parsed = salt.utils.args.parse_input(self.argv[1:], condition=False, no_parse=self.opts.get(u'no_parse', [])) args = parsed[0] kws = parsed[1] return (fun, args, kws)
'Properly escape argument to protect special characters from shell interpretation. This avoids having to do tricky argument quoting. Effectively just escape all characters in the argument that are not alphanumeric!'
def _escape_arg(self, arg):
if self.winrm: return arg return u''.join([((u'\\' + char) if re.match(sdecode('\\W'), char) else char) for char in arg])
'Deploy salt-thin'
def deploy(self):
self.shell.send(self.thin, os.path.join(self.thin_dir, u'salt-thin.tgz')) self.deploy_ext() return True
'Deploy the ext_mods tarball'
def deploy_ext(self):
if self.mods.get(u'file'): self.shell.send(self.mods[u'file'], os.path.join(self.thin_dir, u'salt-ext_mods.tgz')) return True
'Execute the routine, the routine can be either: 1. Execute a raw shell command 2. Execute a wrapper func 3. Execute a remote Salt command If a (re)deploy is needed, then retry the operation after a deploy attempt Returns tuple of (stdout, stderr, retcode)'
def run(self, deploy_attempted=False):
stdout = stderr = retcode = None if self.opts.get(u'raw_shell', False): cmd_str = u' '.join([self._escape_arg(arg) for arg in self.argv]) (stdout, stderr, retcode) = self.shell.exec_cmd(cmd_str) elif ((self.fun in self.wfuncs) or self.mine): (stdout, retcode) = self.run_wfunc() ...
'Execute a wrapper function Returns tuple of (json_data, \'\')'
def run_wfunc(self):
data_cache = False data = None cdir = os.path.join(self.opts[u'cachedir'], u'minions', self.id) if (not os.path.isdir(cdir)): os.makedirs(cdir) datap = os.path.join(cdir, u'ssh_data.p') refresh = False if (not os.path.isfile(datap)): refresh = True else: passed_ti...
'Prepare the command string'
def _cmd_str(self):
sudo = (u'sudo' if self.target[u'sudo'] else u'') sudo_user = self.target[u'sudo_user'] if (u'_caller_cachedir' in self.opts): cachedir = self.opts[u'_caller_cachedir'] else: cachedir = self.opts[u'cachedir'] thin_sum = salt.utils.thin.thin_sum(cachedir, u'sha1') debug = u'' ...
'Run a shim command. If tty is enabled, we must scp the shim to the target system and execute it there'
def shim_cmd(self, cmd_str, extension=u'py'):
if ((not self.tty) and (not self.winrm)): return self.shell.exec_cmd(cmd_str) with tempfile.NamedTemporaryFile(mode=u'w+b', prefix=u'shim_', delete=False) as shim_tmp_file: shim_tmp_file.write(salt.utils.stringutils.to_bytes(cmd_str)) target_shim_file = u'.{0}.{1}'.format(binascii.hexlify(os...
'Prepare the pre-check command to send to the subsystem 1. execute SHIM + command 2. check if SHIM returns a master request or if it completed 3. handle any master request 4. re-execute SHIM + command 5. split SHIM results from command results 6. return command results'
def cmd_block(self, is_retry=False):
self.argv = _convert_args(self.argv) log.debug(u'Performing shimmed, blocking command as follows:\n%s', u' '.join(self.argv)) cmd_str = self._cmd_str() (stdout, stderr, retcode) = self.shim_cmd(cmd_str) log.trace(u'STDOUT %s\n%s', self.target[u'host'], stdout) log.trace(u'ST...
'Stub out check_refresh'
def check_refresh(self, data, ret):
return
'Module refresh is not needed, stub it out'
def module_refresh(self):
return
'Prepare the arguments'
def _prep_ssh(self, tgt, fun, arg=(), timeout=None, tgt_type=u'glob', 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 single command via the salt-ssh subsystem and return a generator .. versionadded:: 2015.5.0'
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...
'Execute a single command via the salt-ssh subsystem and return all routines at once .. versionadded:: 2015.5.0'
def cmd(self, tgt, fun, arg=(), timeout=None, tgt_type=u'glob', 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 salt-ssh call synchronously. .. versionadded:: 2015.5.0 WARNING: Eauth is **NOT** respected .. code-block:: python client.cmd_sync({ \'tgt\': \'silver\', \'fun\': \'test.ping\', \'arg\': (), \'tgt_type\'=\'glob\', \'kwarg\'={} {\'silver\': {\'fun_args\': [], \'jid\': \'20141202152721523072\', \'return\': Tru...
def cmd_sync(self, low):
kwargs = copy.deepcopy(low) for ignore in [u'tgt', u'fun', u'arg', u'timeout', u'tgt_type', u'kwarg']: if (ignore in kwargs): del kwargs[ignore] return self.cmd(low[u'tgt'], low[u'fun'], low.get(u'arg', []), low.get(u'timeout'), low.get(u'tgt_type'), low.get(u'kwarg'), **kwargs)
'Execute aa salt-ssh asynchronously WARNING: Eauth is **NOT** respected .. code-block:: python client.cmd_sync({ \'tgt\': \'silver\', \'fun\': \'test.ping\', \'arg\': (), \'tgt_type\'=\'glob\', \'kwarg\'={} {\'silver\': {\'fun_args\': [], \'jid\': \'20141202152721523072\', \'return\': True, \'retcode\': 0, \'success\':...
def cmd_async(self, low, timeout=None):
raise SaltClientError
'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 >>> import salt.client.ssh.client >>> sshclient= salt.client.ssh.client.SSHClient() >>> sshclient.cmd_s...
def cmd_subset(self, tgt, fun, arg=(), timeout=None, tgt_type=u'glob', ret=u'', kwarg=None, sub=3, **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...
'Parse out an error and return a targeted error string'
def get_error(self, errstr):
for line in errstr.split(u'\n'): if line.startswith(u'ssh:'): return line if line.startswith(u'Pseudo-terminal'): continue if (u'to the list of known hosts.' in line): continue return line return errstr
'Return options for the ssh command base for Salt to call'
def _key_opts(self):
options = [u'KbdInteractiveAuthentication=no'] if self.passwd: options.append(u'PasswordAuthentication=yes') else: options.append(u'PasswordAuthentication=no') if (self.opts.get(u'_ssh_version', (0,)) > (4, 9)): options.append(u'GSSAPIAuthentication=no') options.append(u'Conn...
'Return options to pass to ssh'
def _passwd_opts(self):
options = [u'ControlMaster=auto', u'StrictHostKeyChecking=no'] if (self.opts[u'_ssh_version'] > (4, 9)): options.append(u'GSSAPIAuthentication=no') options.append(u'ConnectTimeout={0}'.format(self.timeout)) if self.opts.get(u'ignore_host_keys'): options.append(u'StrictHostKeyChecking=no'...
'Return the string to execute ssh-copy-id'
def _copy_id_str_old(self):
if self.passwd: return u"{0} {1} '{2} -p {3} {4} {5}@{6}'".format(u'ssh-copy-id', u'-i {0}.pub'.format(self.priv), self._passwd_opts(), self.port, self._ssh_opts(), self.user, self.host) return None
'Since newer ssh-copy-id commands ingest option differently we need to have two commands'
def _copy_id_str_new(self):
if self.passwd: return u'{0} {1} {2} -p {3} {4} {5}@{6}'.format(u'ssh-copy-id', u'-i {0}.pub'.format(self.priv), self._passwd_opts(), self.port, self._ssh_opts(), self.user, self.host) return None
'Execute ssh-copy-id to plant the id file on the target'
def copy_id(self):
(stdout, stderr, retcode) = self._run_cmd(self._copy_id_str_old()) if ((salt.defaults.exitcodes.EX_OK != retcode) and (u'Usage' in stderr)): (stdout, stderr, retcode) = self._run_cmd(self._copy_id_str_new()) return (stdout, stderr, retcode)
'Return the cmd string to execute'
def _cmd_str(self, cmd, ssh=u'ssh'):
command = [ssh] if (ssh != u'scp'): command.append(self.host) if (self.tty and (ssh == u'ssh')): command.append(u'-t -t') if (self.passwd or self.priv): command.append(((self.priv and self._key_opts()) or self._passwd_opts())) if ((ssh != u'scp') and self.remote_port_forwa...
'Cleanly execute the command string'
def _old_run_cmd(self, cmd):
try: proc = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) data = proc.communicate() return (data[0], data[1], proc.returncode) except Exception: return (u'local', u'Unknown Error', None)
'cmd iterator'
def _run_nb_cmd(self, cmd):
try: proc = salt.utils.nb_popen.NonBlockingPopen(cmd, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) while True: time.sleep(0.1) out = proc.recv() err = proc.recv_err() rcode = proc.returncode if ((out is None) and (err is None...
'Yield None until cmd finished'
def exec_nb_cmd(self, cmd):
r_out = [] r_err = [] rcode = None cmd = self._cmd_str(cmd) logmsg = u'Executing non-blocking command: {0}'.format(cmd) if self.passwd: logmsg = logmsg.replace(self.passwd, (u'*' * 6)) log.debug(logmsg) for (out, err, rcode) in self._run_nb_cmd(cmd): if (out is n...
'Execute a remote command'
def exec_cmd(self, cmd):
cmd = self._cmd_str(cmd) logmsg = u'Executing command: {0}'.format(cmd) if self.passwd: logmsg = logmsg.replace(self.passwd, (u'*' * 6)) if ((u'decode("base64")' in logmsg) or (u'base64.b64decode(' in logmsg)): log.debug(u'Executed SHIM command. Command logged to ...
'scp a file or files to a remote system'
def send(self, local, remote, makedirs=False):
if makedirs: self.exec_cmd(u'mkdir -p {0}'.format(os.path.dirname(remote))) host = self.host if (u':' in host): host = u'[{0}]'.format(host) cmd = u'{0} {1}:{2}'.format(local, host, remote) cmd = self._cmd_str(cmd, ssh=u'scp') logmsg = u'Executing command: {0}'.for...
'Execute a shell command via VT. This is blocking and assumes that ssh is being run'
def _run_cmd(self, cmd, key_accept=False, passwd_retries=3):
term = salt.utils.vt.Terminal(cmd, shell=True, log_stdout=True, log_stdout_level=u'trace', log_stderr=True, log_stderr_level=u'trace', stream_stdout=False, stream_stderr=False) sent_passwd = 0 send_password = True ret_stdout = u'' ret_stderr = u'' old_stdout = u'' try: while term.has...
'We need to implement a __contains__ method, othwerwise when someone does a contains comparison python assumes this is a sequence, and does __getitem__ keys 0 and up until IndexError'
def __contains__(self, key):
try: self[key] return True except KeyError: return False
'Return the function call to simulate the salt local lookup system'
def __getitem__(self, cmd):
if ((u'.' not in cmd) and (not self.cmd_prefix)): kwargs = copy.deepcopy(self.kwargs) id_ = kwargs.pop(u'id_') host = kwargs.pop(u'host') return FunctionWrapper(self.opts, id_, host, wfuncs=self.wfuncs, mods=self.mods, fsclient=self.fsclient, cmd_prefix=cmd, aliases=self.aliases, min...
'Set aliases for functions'
def __setitem__(self, cmd, value):
if ((u'.' not in cmd) and (not self.cmd_prefix)): raise KeyError(u'Cannot assign to module key {0} in the FunctionWrapper'.format(cmd)) if self.cmd_prefix: cmd = u'{0}.{1}'.format(self.cmd_prefix, cmd) if (cmd in self.wfuncs): self.wfuncs[cmd] = value self...
'Mirrors behavior of dict.get'
def get(self, cmd, default):
if (cmd in self): return self[cmd] else: return default
'Load up the modules for remote compilation via ssh'
def load_modules(self, data=None, proxy=None):
self.functions = self.wrapper self.utils = salt.loader.utils(self.opts) self.serializers = salt.loader.serializers(self.opts) locals_ = salt.loader.minion_mods(self.opts, utils=self.utils) self.states = salt.loader.states(self.opts, locals_, self.utils, self.serializers) self.rend = salt.loader....
'Stub out check_refresh'
def check_refresh(self, data, ret):
return
'Module refresh is not needed, stub it out'
def module_refresh(self):
return
'Stub out load_dynamic'
def load_dynamic(self, matches):
return
'Evaluate master_tops locally'
def _master_tops(self):
if (u'id' not in self.opts): log.error(u'Received call for external nodes without an id') return {} if (not salt.utils.verify.valid_id(self.opts, self.opts[u'id'])): return {} grains = {} ret = {} if (u'grains' in self.opts): grains = self.opts[u'...
'Run the correct loads serialization format :param encoding: Useful for Python 3 support. If the msgpack data was encoded using "use_bin_type=True", this will differentiate between the \'bytes\' type and the \'str\' type by decoding contents with \'str\' type to what the encoding was set as. Recommended encoding is \'u...
def loads(self, msg, encoding=None, raw=False):
try: gc.disable() if (msgpack.version >= (0, 4, 0)): ret = msgpack.loads(msg, use_list=True, encoding=encoding) else: ret = msgpack.loads(msg, use_list=True) if (six.PY3 and (encoding is None) and (not raw)): ret = salt.transport.frame.decode_embed...
'Run the correct serialization to load a file'
def load(self, fn_):
data = fn_.read() fn_.close() if data: if six.PY3: return self.loads(data, encoding=u'utf-8') else: return self.loads(data)
'Run the correct dumps serialization format :param use_bin_type: Useful for Python 3 support. Tells msgpack to differentiate between \'str\' and \'bytes\' types by encoding them differently. Since this changes the wire protocol, this option should not be used outside of IPC.'
def dumps(self, msg, use_bin_type=False):
try: if (msgpack.version >= (0, 4, 0)): return msgpack.dumps(msg, use_bin_type=use_bin_type) else: return msgpack.dumps(msg) except (OverflowError, msgpack.exceptions.PackValueError): def verylong_encoder(obj): if isinstance(obj, dict): ...
'Serialize the correct data into the named file object'
def dump(self, msg, fn_):
if six.PY2: fn_.write(self.dumps(msg)) else: fn_.write(self.dumps(msg, use_bin_type=True)) fn_.close()
'Lazily create the socket.'
@property def socket(self):
if (not hasattr(self, u'_socket')): self._socket = self.context.socket(zmq.REQ) if hasattr(zmq, u'RECONNECT_IVL_MAX'): self._socket.setsockopt(zmq.RECONNECT_IVL_MAX, 5000) self._set_tcp_keepalive() if self.master.startswith(u'tcp://['): if hasattr(zmq, u'IPV6'...
'delete socket if you have it'
def clear_socket(self):
if hasattr(self, u'_socket'): if isinstance(self.poller.sockets, dict): sockets = list(self.poller.sockets.keys()) for socket in sockets: log.trace(u'Unregistering socket: %s', socket) self.poller.unregister(socket) else: for ...
'Takes two arguments, the encryption type and the base payload'
def send(self, enc, load, tries=1, timeout=60):
payload = {u'enc': enc} payload[u'load'] = load pkg = self.serial.dumps(payload) self.socket.send(pkg) self.poller.register(self.socket, zmq.POLLIN) tried = 0 while True: polled = self.poller.poll((timeout * 1000)) tried += 1 if polled: break if (t...
'Detect the encryption type based on the payload'
def send_auto(self, payload, tries=1, timeout=60):
enc = payload.get(u'enc', u'clear') load = payload.get(u'load', {}) return self.send(enc, load, tries, timeout)
'Evaluate all of the configured beacons, grab the config again in case the pillar or grains changed'
def process_beacons(self, functions):
if (u'config.merge' in functions): b_conf = functions[u'config.merge'](u'beacons', self.opts[u'beacons'], omit_opts=True) if b_conf: return self.beacons.process(b_conf, self.opts[u'grains']) return []
'Evaluates and returns a tuple of the current master address and the pub_channel. In standard mode, just creates a pub_channel with the given master address. With master_type=func evaluates the current master address from the given module and then creates a pub_channel. With master_type=failover takes the list of maste...
@tornado.gen.coroutine def eval_master(self, opts, timeout=60, safe=True, failed=False, failback=False):
if (opts[u'master_type'] == u'disable'): log.warning(u'Master is set to disable, skipping connection') self.connected = False raise tornado.gen.Return((None, None)) elif ((opts[u'master_type'] != u'str') and (opts[u'__role'] != u'syndic')): if (opts[u'master_typ...
'Tell the minion to reload the execution modules CLI Example: .. code-block:: bash salt \'*\' sys.reload_modules'
def gen_modules(self, initial_load=False):
self.opts[u'pillar'] = salt.pillar.get_pillar(self.opts, self.opts[u'grains'], self.opts[u'id'], self.opts[u'environment'], pillarenv=self.opts.get(u'pillarenv')).compile_pillar() self.utils = salt.loader.utils(self.opts) self.functions = salt.loader.minion_mods(self.opts, utils=self.utils) self.seriali...
'Tell the minion to reload the execution modules CLI Example: .. code-block:: bash salt \'*\' sys.reload_modules'
def gen_modules(self, initial_load=False):
self.utils = salt.loader.utils(self.opts) self.functions = salt.loader.minion_mods(self.opts, utils=self.utils, whitelist=self.whitelist, initial_load=initial_load) self.serializers = salt.loader.serializers(self.opts) if self.mk_returners: self.returners = salt.loader.returners(self.opts, self....
'Helper function to return the correct type of object'
def _create_minion_object(self, opts, timeout, safe, io_loop=None, loaded_base_name=None, jid_queue=None):
return Minion(opts, timeout, safe, io_loop=io_loop, loaded_base_name=loaded_base_name, jid_queue=jid_queue)
'Spawn all the coroutines which will sign in to masters'
def _spawn_minions(self):
masters = self.opts[u'master'] if ((self.opts[u'master_type'] == u'failover') or (not isinstance(self.opts[u'master'], list))): masters = [masters] for master in masters: s_opts = copy.deepcopy(self.opts) s_opts[u'master'] = master s_opts[u'multimaster'] = True minion...
'Create a minion, and asynchronously connect it to a master'
@tornado.gen.coroutine def _connect_minion(self, minion):
last = 0 auth_wait = minion.opts[u'acceptance_wait_time'] failed = False while True: try: (yield minion.connect_master(failed=failed)) minion.tune_in(start=False) break except SaltClientError as exc: failed = True log.error(u'Er...
'Bind to the masters This loop will attempt to create connections to masters it hasn\'t connected to yet, but once the initial connection is made it is up to ZMQ to do the reconnect (don\'t know of an API to get the state here in salt)'
def tune_in(self):
self._bind() self._spawn_minions() self.io_loop.start()
'Pass in the options dict'
def __init__(self, opts, timeout=60, safe=True, loaded_base_name=None, io_loop=None, jid_queue=None):
super(Minion, self).__init__(opts) self.timeout = timeout self.safe = safe self._running = None self.win_proc = [] self.loaded_base_name = loaded_base_name self.connected = False self.restart = False self.ready = False self.jid_queue = jid_queue if (io_loop is None): ...
'Block until we are connected to a master'
def sync_connect_master(self, timeout=None, failed=False):
self._sync_connect_master_success = False log.debug(u'sync_connect_master') def on_connect_master_future_done(future): self._sync_connect_master_success = True self.io_loop.stop() self._connect_master_future = self.connect_master(failed=failed) self._connect_master_future.add_done_ca...
'Return a future which will complete when you are connected to a master'
@tornado.gen.coroutine def connect_master(self, failed=False):
(master, self.pub_channel) = (yield self.eval_master(self.opts, self.timeout, self.safe, failed)) (yield self._post_master_init(master))
'Function to finish init after connecting to a master This is primarily loading modules, pillars, etc. (since they need to know which master they connected to) If this function is changed, please check ProxyMinion._post_master_init to see if those changes need to be propagated. Minions and ProxyMinions need significant...
@tornado.gen.coroutine def _post_master_init(self, master):
if self.connected: self.opts[u'master'] = master self.opts[u'pillar'] = (yield salt.pillar.get_async_pillar(self.opts, self.opts[u'grains'], self.opts[u'id'], self.opts[u'environment'], pillarenv=self.opts.get(u'pillarenv')).compile_pillar()) (self.functions, self.returners, self.function_errors...
'Based on the minion configuration, either return a randomized timer or just return the value of the return_retry_timer.'
def _return_retry_timer(self):
msg = u'Minion return retry timer set to {0} seconds' if self.opts.get(u'return_retry_timer_max'): try: random_retry = randint(self.opts[u'return_retry_timer'], self.opts[u'return_retry_timer_max']) log.debug((msg.format(random_retry) + u' (randomized)')) ...
'Returns a copy of the opts with key bits stripped out'
def _prep_mod_opts(self):
mod_opts = {} for (key, val) in six.iteritems(self.opts): if (key == u'logger'): continue mod_opts[key] = val return mod_opts
'Return the functions and the returners loaded up from the loader module'
def _load_modules(self, force_refresh=False, notify=False, grains=None):
modules_max_memory = False if ((self.opts.get(u'modules_max_memory', (-1)) > 0) and HAS_PSUTIL and HAS_RESOURCE): log.debug(u'modules_max_memory set, enforcing a maximum of %s', self.opts[u'modules_max_memory']) modules_max_memory = True old_mem_limit = resource.getrlim...
'Fire an event on the master, or drop message if unable to send.'
def _fire_master(self, data=None, tag=None, events=None, pretag=None, timeout=60, sync=True):
load = {u'id': self.opts[u'id'], u'cmd': u'_minion_event', u'pretag': pretag, u'tok': self.tok} if events: load[u'events'] = events elif (data and tag): load[u'data'] = data load[u'tag'] = tag elif ((not data) and tag): load[u'data'] = {} load[u'tag'] = tag el...
'Override this method if you wish to handle the decoded data differently.'
def _handle_decoded_payload(self, data):
if (u'user' in data): log.info(u'User %s Executing command %s with jid %s', data[u'user'], data[u'fun'], data[u'jid']) else: log.info(u'Executing command %s with jid %s', data[u'fun'], data[u'jid']) log.debug(u'Command details %s', data) log.trac...
'Return a single context manager for the minion\'s data'
def ctx(self):
if six.PY2: return contextlib.nested(self.functions.context_dict.clone(), self.returners.context_dict.clone(), self.executors.context_dict.clone()) else: exitstack = contextlib.ExitStack() exitstack.enter_context(self.functions.context_dict.clone()) exitstack.enter_context(self.r...
'This method should be used as a threading target, start the actual minion side execution.'
@classmethod def _thread_return(cls, minion_instance, opts, data):
fn_ = os.path.join(minion_instance.proc_dir, data[u'jid']) if (opts[u'multiprocessing'] and (not salt.utils.platform.is_windows())): salt.log.setup.shutdown_multiprocessing_logging() salt.utils.daemonize_if(opts) salt.log.setup.setup_multiprocessing_logging() salt.utils.appendproctit...
'This method should be used as a threading target, start the actual minion side execution.'
@classmethod def _thread_multi_return(cls, minion_instance, opts, data):
salt.utils.appendproctitle(u'{0}._thread_multi_return {1}'.format(cls.__name__, data[u'jid'])) ret = {u'return': {}, u'retcode': {}, u'success': {}} for ind in range(0, len(data[u'fun'])): ret[u'success'][data[u'fun'][ind]] = False try: if (minion_instance.connected and minion...
'Return the data from the executed command to the master server'
def _return_pub(self, ret, ret_cmd=u'_return', timeout=60, sync=True):
jid = ret.get(u'jid', ret.get(u'__jid__')) fun = ret.get(u'fun', ret.get(u'__fun__')) if self.opts[u'multiprocessing']: fn_ = os.path.join(self.proc_dir, jid) if os.path.isfile(fn_): try: os.remove(fn_) except (OSError, IOError): pass ...
'Execute a state run based on information set in the minion config file'
def _state_run(self):
if self.opts[u'startup_states']: if ((self.opts.get(u'master_type', u'str') == u'disable') and (self.opts.get(u'file_client', u'remote') == u'remote')): log.warning(u"Cannot run startup_states when 'master_type' is set to 'disable' and 'file_client' is set ...
'Create a loop that will fire a pillar refresh to inform a master about a change in the grains of this minion :param refresh_interval_in_minutes: :return: None'
def _refresh_grains_watcher(self, refresh_interval_in_minutes):
if (u'__update_grains' not in self.opts.get(u'schedule', {})): if (u'schedule' not in self.opts): self.opts[u'schedule'] = {} self.opts[u'schedule'].update({u'__update_grains': {u'function': u'event.fire', u'args': [{}, u'grains_refresh'], u'minutes': refresh_interval_in_minutes}})
'Refresh the functions and returners.'
def module_refresh(self, force_refresh=False, notify=False):
log.debug(u'Refreshing modules. Notify=%s', notify) (self.functions, self.returners, _, self.executors) = self._load_modules(force_refresh, notify=notify) self.schedule.functions = self.functions self.schedule.returners = self.returners
'Refresh the functions and returners.'
def beacons_refresh(self):
log.debug(u'Refreshing beacons.') self.beacons = salt.beacons.Beacon(self.opts, self.functions)
'Refresh the pillar'
@tornado.gen.coroutine def pillar_refresh(self, force_refresh=False):
if self.connected: log.debug(u'Refreshing pillar') try: self.opts[u'pillar'] = (yield salt.pillar.get_async_pillar(self.opts, self.opts[u'grains'], self.opts[u'id'], self.opts[u'environment'], pillarenv=self.opts.get(u'pillarenv')).compile_pillar()) except SaltClientError: ...
'Refresh the functions and returners.'
def manage_schedule(self, tag, data):
func = data.get(u'func', None) name = data.get(u'name', None) schedule = data.get(u'schedule', None) where = data.get(u'where', None) persist = data.get(u'persist', None) if (func == u'delete'): self.schedule.delete_job(name, persist) elif (func == u'add'): self.schedule.add_...
'Manage Beacons'
def manage_beacons(self, tag, data):
func = data.get(u'func', None) name = data.get(u'name', None) beacon_data = data.get(u'beacon_data', None) if (func == u'add'): self.beacons.add_beacon(name, beacon_data) elif (func == u'modify'): self.beacons.modify_beacon(name, beacon_data) elif (func == u'delete'): sel...
'Set the salt-minion main process environment according to the data contained in the minion event data'
def environ_setenv(self, tag, data):
environ = data.get(u'environ', None) if (environ is None): return False false_unsets = data.get(u'false_unsets', False) clear_all = data.get(u'clear_all', False) import salt.modules.environ as mod_environ return mod_environ.setenv(environ, false_unsets, clear_all)
'Set the minion running flag and issue the appropriate warnings if the minion cannot be started or is already running'
def _pre_tune(self):
if (self._running is None): self._running = True elif (self._running is False): log.error(u'This %s was scheduled to stop. Not running %s.tune_in()', self.__class__.__name__, self.__class__.__name__) return elif (self._running is True): log.error(u'Thi...
'Send mine data to the master'
def _mine_send(self, tag, data):
channel = salt.transport.Channel.factory(self.opts) data[u'tok'] = self.tok try: ret = channel.send(data) return ret except SaltReqTimeoutError: log.warning(u'Unable to send mine data to master.') return None
'Handle an event from the epull_sock (all local minion events)'
@tornado.gen.coroutine def handle_event(self, package):
if (not self.ready): raise tornado.gen.Return() (tag, data) = salt.utils.event.SaltEvent.unpack(package) log.debug(u"Minion of '%s' is handling event tag '%s'", self.opts[u'master'], tag) if tag.startswith(u'module_refresh'): self.module_refresh(force_refresh=data.ge...
'Fallback cleanup routines, attempting to fix leaked processes, threads, etc.'
def _fallback_cleanups(self):
multiprocessing.active_children() if (not salt.utils.platform.is_windows()): return for thread in self.win_proc: if (not thread.is_alive()): thread.join() try: self.win_proc.remove(thread) del thread except (ValueError, Name...
'Lock onto the publisher. This is the main event loop for the minion :rtype : None'
def tune_in(self, start=True):
self._pre_tune() log.debug(u"Minion '%s' trying to tune in", self.opts[u'id']) if start: self.sync_connect_master() if self.connected: self._fire_master_minion_start() log.info(u'Minion is ready to receive requests!') enable_sigusr1_handler() ...
'Tear down the minion'
def destroy(self):
self._running = False if hasattr(self, u'schedule'): del self.schedule if (hasattr(self, u'pub_channel') and (self.pub_channel is not None)): self.pub_channel.on_recv(None) if hasattr(self.pub_channel, u'close'): self.pub_channel.close() del self.pub_channel i...
'Override this method if you wish to handle the decoded data differently.'
def _handle_decoded_payload(self, data):
data[u'to'] = (int(data.get(u'to', self.opts[u'timeout'])) - 1) if (data.get(u'master_id', 0) != self.opts.get(u'master_id', 1)): self.syndic_cmd(data)
'Take the now clear load and forward it on to the client cmd'
def syndic_cmd(self, data):
if (u'tgt_type' not in data): data[u'tgt_type'] = u'glob' kwargs = {} for field in (u'master_id', u'user'): if (field in data): kwargs[field] = data[field] def timeout_handler(*args): log.warning(u'Unable to forward pub data: %s', args[1]) retur...
'Executes the tune_in sequence but omits extra logging and the management of the event bus assuming that these are handled outside the tune_in sequence'
def tune_in_no_block(self):
self.local = salt.client.get_local_client(self.opts[u'_minion_conf_file'], io_loop=self.io_loop) self.pub_channel.on_recv(self._process_cmd_socket)