Generic call of salt Caller command
507746
def _call_salt_command(self,
                           fun,
                           args,
                           kwargs,
                           assertion_section=None):
        '''
        
        '''
        value = False
        try:
            if args and kwargs:
                value = self.salt_lc.cmd(fun, *args, **kwargs)
            elif args and not kwargs:
                value = self.salt_lc.cmd(fun, *args)
            elif not args and kwargs:
                value = self.salt_lc.cmd(fun, **kwargs)
            else:
                value = self.salt_lc.cmd(fun)
        except salt.exceptions.SaltException:
            raise
        except Exception:
            raise
        if isinstance(value, dict) and assertion_section:
            return value.get(assertion_section, False)
        else:
            return value
142268
def salt_api():
    '''
    
    '''
    import salt.utils.process
    salt.utils.process.notify_systemd()

    import salt.cli.api
    sapi = salt.cli.api.SaltAPI()  # pylint: disable=E1120
    sapi.start()
1303219
def _run_command(cmd, options=(), env=None):
    '''
    
    '''
    params = [cmd]
    params.extend(options)
    return __salt__['cmd.run_all'](params, env=env, python_shell=False)
300750
def execution():
    '''
    
    '''
    client = salt.client.get_local_client(__opts__['conf_file'])

    docs = {}
    try:
        for ret in client.cmd_iter('*', 'sys.doc', timeout=__opts__['timeout']):
            for v in six.itervalues(ret):
                docs.update(v)
    except SaltClientError as exc:
        print(exc)
        return []

    i = itertools.chain.from_iterable([six.iteritems(docs['ret'])])
    ret = dict(list(i))

    return ret
166054
def _restripe(mountpoint, direction, *devices, **kwargs):
    '''
    
    '''
    fs_log = []

    if salt.utils.fsutils._is_device(mountpoint):
        raise CommandExecutionError(
            "Mountpount expected, while device \"{0}\" specified".format(mountpoint))

    mounted = False
    for device, mntpoints in six.iteritems(salt.utils.fsutils._get_mounts("btrfs")):
        for mntdata in mntpoints:
            if mntdata['mount_point'] == mountpoint:
                mounted = True
                break

    if not mounted:
        raise CommandExecutionError(
            "No BTRFS device mounted on \"{0}\" mountpoint".format(mountpoint))

    if not devices:
        raise CommandExecutionError("No devices specified.")

    available_devices = __salt__['btrfs.devices']()
    for device in devices:
        if device not in six.iterkeys(available_devices):
            raise CommandExecutionError("Device \"{0}\" is not recognized".format(device))

    cmd = ['btrfs device {0}'.format(direction)]
    for device in devices:
        cmd.append(device)

    if direction == 'add':
        if kwargs.get("nodiscard"):
            cmd.append("-K")
        if kwargs.get("force"):
            cmd.append("-f")

    cmd.append(mountpoint)

    out = __salt__['cmd.run_all'](' '.join(cmd))
    salt.utils.fsutils._verify_run(out)
    if out['stdout']:
        fs_log.append(out['stdout'])

    if direction == 'add':
        out = None
        data_conversion = kwargs.get("dc")
        meta_conversion = kwargs.get("mc")
        if data_conversion and meta_conversion:
            out = __salt__['cmd.run_all'](
                "btrfs balance start -dconvert={0} -mconvert={1} {2}".format(
                    data_conversion, meta_conversion, mountpoint))
        else:
            out = __salt__['cmd.run_all']("btrfs filesystem balance {0}".format(mountpoint))
        salt.utils.fsutils._verify_run(out)
        if out['stdout']:
            fs_log.append(out['stdout'])

    # Summarize the result
    ret = {}
    if fs_log:
        ret.update({'log': '\n'.join(fs_log)})
    ret.update(__salt__['btrfs.info'](mountpoint))

    return ret
1083748
def on_command_call(receiver, dot, method, args)
      if is_ident?(method) &&
              (constant = resolve_constant_ref(receiver))
        method_call(method, [constant])
      end
      keep_walking(receiver, args)
    end
402336
def destroy(name, call=None):
    '''
    
    '''
    if call == 'function':
        raise SaltCloudSystemExit(
            'The destroy action must be called with -d, --destroy, '
            '-a or --action.'
        )

    __utils__['cloud.fire_event'](
        'event',
        'destroying instance',
        'salt/cloud/{0}/destroying'.format(name),
        args={'name': name},
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    node = show_instance(name, call='action')
    if node['state'] == 'STARTED':
        stop(name, call='action')
        if not wait_until(name, 'STOPPED'):
            return {
                'Error': 'Unable to destroy {0}, command timed out'.format(
                    name
                )
            }

    data = query(action='ve', command=name, method='DELETE')

    if 'error' in data:
        return data['error']

    __utils__['cloud.fire_event'](
        'event',
        'destroyed instance',
        'salt/cloud/{0}/destroyed'.format(name),
        args={'name': name},
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    if __opts__.get('update_cachedir', False) is True:
        __utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)

    return {'Destroyed': '{0} was destroyed.'.format(name)}
941785
def return_pub(self, ret):
        '''
        
        '''
        channel = salt.transport.client.ReqChannel.factory(self.opts, usage='salt_call')
        load = {'cmd': '_return', 'id': self.opts['id']}
        for key, value in six.iteritems(ret):
            load[key] = value
        try:
            channel.send(load)
        finally:
            channel.close()
628280
def _call_brew(cmd, failhard=True):
    '''
    
    '''
    user = __salt__['file.get_user'](_homebrew_bin())
    runas = user if user != __opts__['user'] else None
    cmd = '{} {}'.format(salt.utils.path.which('brew'), cmd)
    result = __salt__['cmd.run_all'](cmd,
                                     runas=runas,
                                     output_loglevel='trace',
                                     python_shell=False)
    if failhard and result['retcode'] != 0:
        raise CommandExecutionError('Brew command failed',
                                    info={'result': result})
    return result
288439
function (cwd = process.cwd()) {
        const promise = new Promise((resolve, reject) => {
            const _name = this.toString();
            // eslint-disable-next-line no-console
            console.log(`spawning:: ${_name}`);
            const call = spawn(this.cmd, this.args, {env: process.env, shell: true, stdio: 'inherit', cwd});
            this.args = [];
            call.on('exit', (code) => {
                // eslint-disable-next-line no-console
                console.log(`spawning:: ${_name} code::${code}`);
                if (code === 0) {
                    resolve(0);
                } else {
                    reject(code);
                }
            });
            return call;
        });

        return promise;
    }
3626
def handle_func(self, multiprocessing_enabled, func, data):
        '''
        
        '''
        if salt.utils.platform.is_windows() \
                or self.opts.get('transport') == 'zeromq':
            # Since function references can't be pickled and pickling
            # is required when spawning new processes on Windows, regenerate
            # the functions and returners.
            # This also needed for ZeroMQ transport to reset all functions
            # context data that could keep paretns connections. ZeroMQ will
            # hang on polling parents connections from the child process.
            if self.opts['__role'] == 'master':
                self.functions = salt.loader.runner(self.opts, utils=self.utils)
            else:
                self.functions = salt.loader.minion_mods(self.opts, proxy=self.proxy, utils=self.utils)
            self.returners = salt.loader.returners(self.opts, self.functions, proxy=self.proxy)
        ret = {'id': self.opts.get('id', 'master'),
               'fun': func,
               'fun_args': [],
               'schedule': data['name'],
               'jid': salt.utils.jid.gen_jid(self.opts)}

        if 'metadata' in data:
            if isinstance(data['metadata'], dict):
                ret['metadata'] = data['metadata']
                ret['metadata']['_TOS'] = self.time_offset
                ret['metadata']['_TS'] = time.ctime()
                ret['metadata']['_TT'] = time.strftime('%Y %B %d %a %H %m', time.gmtime())
            else:
                log.warning('schedule: The metadata parameter must be '
                            'specified as a dictionary.  Ignoring.')

        if multiprocessing_enabled:
            # We just want to modify the process name if we're on a different process
            salt.utils.process.appendproctitle('{0} {1}'.format(self.__class__.__name__, ret['jid']))
        data_returner = data.get('returner', None)

        if not self.standalone:
            proc_fn = os.path.join(
                salt.minion.get_proc_dir(self.opts['cachedir']),
                ret['jid']
            )

        if multiprocessing_enabled and not salt.utils.platform.is_windows():
            # Reconfigure multiprocessing logging after daemonizing
            log_setup.setup_multiprocessing_logging()

        if multiprocessing_enabled:
            # Don't *BEFORE* to go into try to don't let it triple execute the finally section.
            salt.utils.process.daemonize_if(self.opts)

        # TODO: Make it readable! Splt to funcs, remove nested try-except-finally sections.
        try:

            minion_blackout_violation = False
            if self.opts.get('pillar', {}).get('minion_blackout', False):
                whitelist = self.opts.get('pillar', {}).get('minion_blackout_whitelist', [])
                # this minion is blacked out. Only allow saltutil.refresh_pillar and the whitelist
                if func != 'saltutil.refresh_pillar' and func not in whitelist:
                    minion_blackout_violation = True
            elif self.opts.get('grains', {}).get('minion_blackout', False):
                whitelist = self.opts.get('grains', {}).get('minion_blackout_whitelist', [])
                if func != 'saltutil.refresh_pillar' and func not in whitelist:
                    minion_blackout_violation = True
            if minion_blackout_violation:
                raise SaltInvocationError('Minion in blackout mode. Set \'minion_blackout\' '
                                          'to False in pillar or grains to resume operations. Only '
                                          'saltutil.refresh_pillar allowed in blackout mode.')

            ret['pid'] = os.getpid()

            if not self.standalone:
                if 'jid_include' not in data or data['jid_include']:
                    log.debug(
                        'schedule.handle_func: adding this job to the '
                        'jobcache with data %s', ret
                    )
                    # write this to /var/cache/salt/minion/proc
                    with salt.utils.files.fopen(proc_fn, 'w+b') as fp_:
                        fp_.write(salt.payload.Serial(self.opts).dumps(ret))

            args = tuple()
            if 'args' in data:
                args = data['args']
                ret['fun_args'].extend(data['args'])

            kwargs = {}
            if 'kwargs' in data:
                kwargs = data['kwargs']
                ret['fun_args'].append(copy.deepcopy(kwargs))

            if func not in self.functions:
                ret['return'] = self.functions.missing_fun_string(func)
                salt.utils.error.raise_error(
                    message=self.functions.missing_fun_string(func))

            # if the func support **kwargs, lets pack in the pub data we have
            # TODO: pack the *same* pub data as a minion?
            argspec = salt.utils.args.get_function_argspec(self.functions[func])
            if argspec.keywords:
                # this function accepts **kwargs, pack in the publish data
                for key, val in six.iteritems(ret):
                    if key is not 'kwargs':
                        kwargs['__pub_{0}'.format(key)] = copy.deepcopy(val)

            # Only include these when running runner modules
            if self.opts['__role'] == 'master':
                jid = salt.utils.jid.gen_jid(self.opts)
                tag = salt.utils.event.tagify(jid, prefix='salt/scheduler/')

                event = salt.utils.event.get_event(
                        self.opts['__role'],
                        self.opts['sock_dir'],
                        self.opts['transport'],
                        opts=self.opts,
                        listen=False)

                namespaced_event = salt.utils.event.NamespacedEvent(
                    event,
                    tag,
                    print_func=None
                )

                func_globals = {
                    '__jid__': jid,
                    '__user__': salt.utils.user.get_user(),
                    '__tag__': tag,
                    '__jid_event__': weakref.proxy(namespaced_event),
                }
                self_functions = copy.copy(self.functions)
                salt.utils.lazy.verify_fun(self_functions, func)

                # Inject some useful globals to *all* the function's global
                # namespace only once per module-- not per func
                completed_funcs = []

                for mod_name in six.iterkeys(self_functions):
                    if '.' not in mod_name:
                        continue
                    mod, _ = mod_name.split('.', 1)
                    if mod in completed_funcs:
                        continue
                    completed_funcs.append(mod)
                    for global_key, value in six.iteritems(func_globals):
                        self.functions[mod_name].__globals__[global_key] = value

            self.functions.pack['__context__']['retcode'] = 0

            ret['return'] = self.functions[func](*args, **kwargs)

            if not self.standalone:
                # runners do not provide retcode
                if 'retcode' in self.functions.pack['__context__']:
                    ret['retcode'] = self.functions.pack['__context__']['retcode']

                ret['success'] = True

                if data_returner or self.schedule_returner:
                    if 'return_config' in data:
                        ret['ret_config'] = data['return_config']
                    if 'return_kwargs' in data:
                        ret['ret_kwargs'] = data['return_kwargs']
                    rets = []
                    for returner in [data_returner, self.schedule_returner]:
                        if isinstance(returner, six.string_types):
                            rets.append(returner)
                        elif isinstance(returner, list):
                            rets.extend(returner)
                    # simple de-duplication with order retained
                    for returner in OrderedDict.fromkeys(rets):
                        ret_str = '{0}.returner'.format(returner)
                        if ret_str in self.returners:
                            self.returners[ret_str](ret)
                        else:
                            log.info(
                                'Job %s using invalid returner: %s. Ignoring.',
                                func, returner
                            )

        except Exception:
            log.exception('Unhandled exception running %s', ret['fun'])
            # Although catch-all exception handlers are bad, the exception here
            # is to let the exception bubble up to the top of the thread context,
            # where the thread will die silently, which is worse.
            if 'return' not in ret:
                ret['return'] = "Unhandled exception running {0}".format(ret['fun'])
            ret['success'] = False
            ret['retcode'] = 254
        finally:
            # Only attempt to return data to the master if the scheduled job is running
            # on a master itself or a minion.
            if '__role' in self.opts and self.opts['__role'] in ('master', 'minion'):
                # The 'return_job' option is enabled by default even if not set
                if 'return_job' in data and not data['return_job']:
                    pass
                else:
                    # Send back to master so the job is included in the job list
                    mret = ret.copy()
                    # No returners defined, so we're only sending back to the master
                    if not data_returner and not self.schedule_returner:
                        mret['jid'] = 'req'
                        if data.get('return_job') == 'nocache':
                            # overwrite 'req' to signal to master that
                            # this job shouldn't be stored
                            mret['jid'] = 'nocache'
                    load = {'cmd': '_return', 'id': self.opts['id']}
                    for key, value in six.iteritems(mret):
                        load[key] = value

                    if '__role' in self.opts and self.opts['__role'] == 'minion':
                        event = salt.utils.event.get_event('minion',
                                                           opts=self.opts,
                                                           listen=False)
                    elif '__role' in self.opts and self.opts['__role'] == 'master':
                        event = salt.utils.event.get_master_event(self.opts,
                                                                  self.opts['sock_dir'])
                    try:
                        event.fire_event(load, '__schedule_return')
                    except Exception as exc:
                        log.exception('Unhandled exception firing __schedule_return event')

            if not self.standalone:
                log.debug('schedule.handle_func: Removing %s', proc_fn)

                try:
                    os.unlink(proc_fn)
                except OSError as exc:
                    if exc.errno == errno.EEXIST or exc.errno == errno.ENOENT:
                        # EEXIST and ENOENT are OK because the file is gone and that's what
                        # we wanted
                        pass
                    else:
                        log.error("Failed to delete '%s': %s", proc_fn, exc.errno)
                        # Otherwise, failing to delete this file is not something
                        # we can cleanly handle.
                        raise
                finally:
                    if multiprocessing_enabled:
                        # Let's make sure we exit the process!
                        sys.exit(salt.defaults.exitcodes.EX_GENERIC)
1218629
def returner(ret):
    '''
    
    '''

    _options = _get_options(ret)

    api_url = _options.get('api_url')
    channel = _options.get('channel')
    username = _options.get('username')
    hook = _options.get('hook')

    if not hook:
        log.error('mattermost.hook not defined in salt config')
        return

    returns = ret.get('return')

    message = ('id: {0}\r\n'
               'function: {1}\r\n'
               'function args: {2}\r\n'
               'jid: {3}\r\n'
               'return: {4}\r\n').format(
                    ret.get('id'),
                    ret.get('fun'),
                    ret.get('fun_args'),
                    ret.get('jid'),
                    returns)

    mattermost = post_message(channel,
                              message,
                              username,
                              api_url,
                              hook)
    return mattermost
618915
def salt_key():
    '''
    
    '''
    import salt.cli.key
    try:
        client = salt.cli.key.SaltKey()
        _install_signal_handlers(client)
        client.run()
    except Exception as err:
        sys.stderr.write("Error: {0}\n".format(err))
1050896
def salt_proxy():
    '''
    
    '''
    import salt.cli.daemons
    import salt.utils.platform
    import multiprocessing
    if '' in sys.path:
        sys.path.remove('')

    if salt.utils.platform.is_windows():
        proxyminion = salt.cli.daemons.ProxyMinion()
        proxyminion.start()
        return

    if '--disable-keepalive' in sys.argv:
        sys.argv.remove('--disable-keepalive')
        proxyminion = salt.cli.daemons.ProxyMinion()
        proxyminion.start()
        return

    # keep one minion subprocess running
    while True:
        try:
            queue = multiprocessing.Queue()
        except Exception:
            # This breaks in containers
            proxyminion = salt.cli.daemons.ProxyMinion()
            proxyminion.start()
            return
        process = multiprocessing.Process(target=proxy_minion_process, args=(queue,))
        process.start()
        try:
            process.join()
            try:
                restart_delay = queue.get(block=False)
            except Exception:
                if process.exitcode == 0:
                    # Minion process ended naturally, Ctrl+C or --version
                    break
                restart_delay = 60
            if restart_delay == 0:
                # Minion process ended naturally, Ctrl+C, --version, etc.
                sys.exit(process.exitcode)
            # delay restart to reduce flooding and allow network resources to close
            time.sleep(restart_delay)
        except KeyboardInterrupt:
            break
        # need to reset logging because new minion objects
        # cause extra log handlers to accumulate
        rlogger = logging.getLogger()
        for handler in rlogger.handlers:
            rlogger.removeHandler(handler)
        logging.basicConfig()
295734
def run(self, low):
        '''
        
        '''
        # Eauth currently requires a running daemon and commands run through
        # this method require eauth so perform a quick check to raise a
        # more meaningful error.
        if not self._is_master_running():
            raise salt.exceptions.SaltDaemonNotRunning(
                    'Salt Master is not available.')

        if low.get('client') not in CLIENTS:
            raise salt.exceptions.SaltInvocationError(
                    'Invalid client specified: \'{0}\''.format(low.get('client')))

        if not ('token' in low or 'eauth' in low) and low['client'] != 'ssh':
            raise salt.exceptions.EauthAuthenticationError(
                    'No authentication credentials given')

        l_fun = getattr(self, low['client'])
        f_call = salt.utils.args.format_call(l_fun, low)
        return l_fun(*f_call.get('args', ()), **f_call.get('kwargs', {}))
521989
def gen_salt(length):
    """"""
    if length <= 0:
        raise ValueError('requested salt of length <= 0')
    return ''.join(_sys_rng.choice(SALT_CHARS) for _ in range_type(length))
217770
def reboot(name, call=None):
    '''
    
    '''

    if call != 'action':
        raise SaltCloudException(
            'The reboot action must be called with -a or --action.'
        )

    local = salt.client.LocalClient()
    return local.cmd(name, 'system.reboot')