Publish commands to the salt system from the command line on the
    master.
423205
def salt_cp():
    '''
    
    '''
    import salt.cli.cp
    client = salt.cli.cp.SaltCPCli()
    _install_signal_handlers(client)
    client.run()
655611
def deploy(self):
        '''
        
        '''
        self.shell.send(
            self.thin,
            os.path.join(self.thin_dir, 'salt-thin.tgz'),
        )
        self.deploy_ext()
        return True
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', {}))
67907
def add(event, reactors, saltenv='base', test=None):
    '''
    
    '''
    if isinstance(reactors, string_types):
        reactors = [reactors]

    sevent = salt.utils.event.get_event(
            'master',
            __opts__['sock_dir'],
            __opts__['transport'],
            opts=__opts__,
            listen=True)

    master_key = salt.utils.master.get_master_key('root', __opts__)

    __jid_event__.fire_event({'event': event,
                              'reactors': reactors,
                              'key': master_key},
                             'salt/reactors/manage/add')

    res = sevent.get_event(wait=30, tag='salt/reactors/manage/add-complete')
    return res['result']
428537
def __execute_cmd(command, host=None,
                  admin_username=None, admin_password=None,
                  module=None):
    '''
    
    '''
    if module:
        # -a takes 'server' or 'switch' to represent all servers
        # or all switches in a chassis.  Allow
        # user to say 'module=ALL_SERVER' or 'module=ALL_SWITCH'
        if module.startswith('ALL_'):
            modswitch = '-a '\
                        + module[module.index('_') + 1:len(module)].lower()
        else:
            modswitch = '-m {0}'.format(module)
    else:
        modswitch = ''
    if not host:
        # This is a local call
        cmd = __salt__['cmd.run_all']('racadm {0} {1}'.format(command,
                                                              modswitch))
    else:
        cmd = __salt__['cmd.run_all'](
            'racadm -r {0} -u {1} -p {2} {3} {4}'.format(host,
                                                         admin_username,
                                                         admin_password,
                                                         command,
                                                         modswitch),
        output_loglevel='quiet')

    if cmd['retcode'] != 0:
        log.warning('racadm returned an exit code of %s', cmd['retcode'])
        return False

    return True
199060
def send(self, commands):
        ""
        if not commands.endswith("\n"):
            commands += "\n"
        self.sock.send(commands)
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
1298544
def publish(self, load):
        '''
        
        '''
        payload = {'enc': 'aes'}

        crypticle = salt.crypt.Crypticle(self.opts, salt.master.SMaster.secrets['aes']['secret'].value)
        payload['load'] = crypticle.dumps(load)
        if self.opts['sign_pub_messages']:
            master_pem_path = os.path.join(self.opts['pki_dir'], 'master.pem')
            log.debug("Signing data packet")
            payload['sig'] = salt.crypt.sign_message(master_pem_path, payload['load'])
        # Use the Salt IPC server
        if self.opts.get('ipc_mode', '') == 'tcp':
            pull_uri = int(self.opts.get('tcp_master_publish_pull', 4514))
        else:
            pull_uri = os.path.join(self.opts['sock_dir'], 'publish_pull.ipc')
        # TODO: switch to the actual asynchronous interface
        #pub_sock = salt.transport.ipc.IPCMessageClient(self.opts, io_loop=self.io_loop)
        pub_sock = salt.utils.asynchronous.SyncWrapper(
            salt.transport.ipc.IPCMessageClient,
            (pull_uri,)
        )
        pub_sock.connect()

        int_payload = {'payload': self.serial.dumps(payload)}

        # add some targeting stuff for lists only (for now)
        if load['tgt_type'] == 'list':
            if isinstance(load['tgt'], six.string_types):
                # Fetch a list of minions that match
                _res = self.ckminions.check_minions(load['tgt'],
                                                    tgt_type=load['tgt_type'])
                match_ids = _res['minions']

                log.debug("Publish Side Match: %s", match_ids)
                # Send list of miions thru so zmq can target them
                int_payload['topic_lst'] = match_ids
            else:
                int_payload['topic_lst'] = load['tgt']
        # Send it over IPC!
        pub_sock.send(int_payload)
296293
def _run_psql(cmd, runas=None, password=None, host=None, port=None, user=None):
    '''
    
    '''
    kwargs = {
        'reset_system_locale': False,
        'clean_env': True,
    }
    if runas is None:
        if not host:
            host = __salt__['config.option']('postgres.host')
        if not host or host.startswith('/'):
            if 'FreeBSD' in __grains__['os_family']:
                runas = 'pgsql'
            elif 'OpenBSD' in __grains__['os_family']:
                runas = '_postgresql'
            else:
                runas = 'postgres'

    if user is None:
        user = runas

    if runas:
        kwargs['runas'] = runas

    if password is None:
        password = __salt__['config.option']('postgres.pass')
    if password is not None:
        pgpassfile = salt.utils.files.mkstemp(text=True)
        with salt.utils.files.fopen(pgpassfile, 'w') as fp_:
            fp_.write(salt.utils.stringutils.to_str('{0}:{1}:*:{2}:{3}'.format(
                'localhost' if not host or host.startswith('/') else host,
                port if port else '*',
                user if user else '*',
                password,
            )))
            __salt__['file.chown'](pgpassfile, runas, '')
            kwargs['env'] = {'PGPASSFILE': pgpassfile}

    ret = __salt__['cmd.run_all'](cmd, python_shell=False, **kwargs)

    if ret.get('retcode', 0) != 0:
        log.error('Error connecting to Postgresql server')
    if password is not None and not __salt__['file.remove'](pgpassfile):
        log.warning('Remove PGPASSFILE failed')

    return ret
845437
def salt(self, module, target='*', args=None, kwargs=None, ssh=False):
        
        if ssh:
            return salt.salt_ssh(self, target, module, args, kwargs)
        else:
            return salt.salt_master(self, target, module, args, kwargs)
1279892
def _exec(**kwargs):
    '''
    
    '''
    if 'ignore_retcode' not in kwargs:
        kwargs['ignore_retcode'] = True
    if 'output_loglevel' not in kwargs:
        kwargs['output_loglevel'] = 'quiet'
    return salt.modules.cmdmod.run_all(**kwargs)
1266780
def run(self):
        '''
        
        '''
        import salt.key
        self.parse_args()

        self.setup_logfile_logger()
        verify_log(self.config)

        key = salt.key.KeyCLI(self.config)
        if check_user(self.config['user']):
            key.run()
920172
def run_command(self):
        """"""
        topics = get_topic_partition_metadata(self.cluster_config.broker_list)

        topics_with_wrong_rf = _find_topics_with_wrong_rp(
            topics,
            self.zk,
            self.args.default_min_isr,
        )

        errcode = status_code.OK if not topics_with_wrong_rf else status_code.CRITICAL
        out = _prepare_output(topics_with_wrong_rf, self.args.verbose)
        return errcode, out
1061873
def cli(ctx, board, serial_port, ftdi_id, sram, project_dir,
        verbose, verbose_yosys, verbose_arachne):
    """"""

    drivers = Drivers()
    drivers.pre_upload()
    # Run scons
    exit_code = SCons(project_dir).upload({
        'board': board,
        'verbose': {
            'all': verbose,
            'yosys': verbose_yosys,
            'arachne': verbose_arachne
        }
    }, serial_port, ftdi_id, sram)
    drivers.post_upload()
    ctx.exit(exit_code)
72889
def run(self):
        '''
        
        '''
        import salt.client
        self.parse_args()

        if self.config['log_level'] not in ('quiet', ):
            # Setup file logging!
            self.setup_logfile_logger()
            verify_log(self.config)

        try:
            # We don't need to bail on config file permission errors
            # if the CLI process is run with the -a flag
            skip_perm_errors = self.options.eauth != ''

            self.local_client = salt.client.get_local_client(
                self.get_config_file_path(),
                skip_perm_errors=skip_perm_errors,
                auto_reconnect=True)
        except SaltClientError as exc:
            self.exit(2, '{0}\n'.format(exc))
            return

        if self.options.batch or self.options.static:
            # _run_batch() will handle all output and
            # exit with the appropriate error condition
            # Execution will not continue past this point
            # in batch mode.
            self._run_batch()
            return

        if self.options.preview_target:
            minion_list = self._preview_target()
            self._output_ret(minion_list, self.config.get('output', 'nested'))
            return

        if self.options.timeout <= 0:
            self.options.timeout = self.local_client.opts['timeout']

        kwargs = {
            'tgt': self.config['tgt'],
            'fun': self.config['fun'],
            'arg': self.config['arg'],
            'timeout': self.options.timeout,
            'show_timeout': self.options.show_timeout,
            'show_jid': self.options.show_jid}

        if 'token' in self.config:
            import salt.utils.files
            try:
                with salt.utils.files.fopen(os.path.join(self.config['cachedir'], '.root_key'), 'r') as fp_:
                    kwargs['key'] = fp_.readline()
            except IOError:
                kwargs['token'] = self.config['token']

        kwargs['delimiter'] = self.options.delimiter

        if self.selected_target_option:
            kwargs['tgt_type'] = self.selected_target_option
        else:
            kwargs['tgt_type'] = 'glob'

        # If batch_safe_limit is set, check minions matching target and
        # potentially switch to batch execution
        if self.options.batch_safe_limit > 1:
            if len(self._preview_target()) >= self.options.batch_safe_limit:
                salt.utils.stringutils.print_cli('\nNOTICE: Too many minions targeted, switching to batch execution.')
                self.options.batch = self.options.batch_safe_size
                self._run_batch()
                return

        if getattr(self.options, 'return'):
            kwargs['ret'] = getattr(self.options, 'return')

        if getattr(self.options, 'return_config'):
            kwargs['ret_config'] = getattr(self.options, 'return_config')

        if getattr(self.options, 'return_kwargs'):
            kwargs['ret_kwargs'] = yamlify_arg(
                    getattr(self.options, 'return_kwargs'))

        if getattr(self.options, 'module_executors'):
            kwargs['module_executors'] = yamlify_arg(getattr(self.options, 'module_executors'))

        if getattr(self.options, 'executor_opts'):
            kwargs['executor_opts'] = yamlify_arg(getattr(self.options, 'executor_opts'))

        if getattr(self.options, 'metadata'):
            kwargs['metadata'] = yamlify_arg(
                    getattr(self.options, 'metadata'))

        # If using eauth and a token hasn't already been loaded into
        # kwargs, prompt the user to enter auth credentials
        if 'token' not in kwargs and 'key' not in kwargs and self.options.eauth:
            # This is expensive. Don't do it unless we need to.
            import salt.auth
            resolver = salt.auth.Resolver(self.config)
            res = resolver.cli(self.options.eauth)
            if self.options.mktoken and res:
                tok = resolver.token_cli(
                        self.options.eauth,
                        res
                        )
                if tok:
                    kwargs['token'] = tok.get('token', '')
            if not res:
                sys.stderr.write('ERROR: Authentication failed\n')
                sys.exit(2)
            kwargs.update(res)
            kwargs['eauth'] = self.options.eauth

        if self.config['async']:
            jid = self.local_client.cmd_async(**kwargs)
            salt.utils.stringutils.print_cli('Executed command with job ID: {0}'.format(jid))
            return

        # local will be None when there was an error
        if not self.local_client:
            return

        retcodes = []
        errors = []

        try:
            if self.options.subset:
                cmd_func = self.local_client.cmd_subset
                kwargs['sub'] = self.options.subset
                kwargs['cli'] = True
            else:
                cmd_func = self.local_client.cmd_cli

            if self.options.progress:
                kwargs['progress'] = True
                self.config['progress'] = True
                ret = {}
                for progress in cmd_func(**kwargs):
                    out = 'progress'
                    try:
                        self._progress_ret(progress, out)
                    except LoaderError as exc:
                        raise SaltSystemExit(exc)
                    if 'return_count' not in progress:
                        ret.update(progress)
                self._progress_end(out)
                self._print_returns_summary(ret)
            elif self.config['fun'] == 'sys.doc':
                ret = {}
                out = ''
                for full_ret in self.local_client.cmd_cli(**kwargs):
                    ret_, out, retcode = self._format_ret(full_ret)
                    ret.update(ret_)
                self._output_ret(ret, out, retcode=retcode)
            else:
                if self.options.verbose:
                    kwargs['verbose'] = True
                ret = {}
                for full_ret in cmd_func(**kwargs):
                    try:
                        ret_, out, retcode = self._format_ret(full_ret)
                        retcodes.append(retcode)
                        self._output_ret(ret_, out, retcode=retcode)
                        ret.update(full_ret)
                    except KeyError:
                        errors.append(full_ret)

            # Returns summary
            if self.config['cli_summary'] is True:
                if self.config['fun'] != 'sys.doc':
                    if self.options.output is None:
                        self._print_returns_summary(ret)
                        self._print_errors_summary(errors)

            # NOTE: Return code is set here based on if all minions
            # returned 'ok' with a retcode of 0.
            # This is the final point before the 'salt' cmd returns,
            # which is why we set the retcode here.
            if not all(exit_code == salt.defaults.exitcodes.EX_OK for exit_code in retcodes):
                sys.stderr.write('ERROR: Minions returned with non-zero exit code\n')
                sys.exit(salt.defaults.exitcodes.EX_GENERIC)

        except (AuthenticationError,
                AuthorizationError,
                SaltInvocationError,
                EauthAuthenticationError,
                SaltClientError) as exc:
            ret = six.text_type(exc)
            self._output_ret(ret, '', retcode=1)
835014
def master_call(self, **kwargs):
        '''
        
        '''
        load = kwargs
        load['cmd'] = self.client
        channel = salt.transport.client.ReqChannel.factory(self.opts,
                                                           crypt='clear',
                                                           usage='master_call')
        try:
            ret = channel.send(load)
        finally:
            channel.close()
        if isinstance(ret, collections.Mapping):
            if 'error' in ret:
                salt.utils.error.raise_error(**ret['error'])
        return ret
304489
def generate(command,
             name,
             init_system,
             overwrite,
             deploy,
             start,
             verbose,
             **params):
    
    # TODO: Add a `prefix` flag which can be used to prefix
    # `COMMAND` with `su -c`, etc..
    try:
        Serv(init_system, verbose=verbose).generate(
            command, name, overwrite, deploy, start, **params)
    except ServError as ex:
        sys.exit(ex)