• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python client.cmd_iter函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中salt.client.cmd_iter函数的典型用法代码示例。如果您正苦于以下问题:Python cmd_iter函数的具体用法?Python cmd_iter怎么用?Python cmd_iter使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了cmd_iter函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: query

def query(hyper=None, quiet=False):
    """
    Query the virtual machines
    """
    ret = {}
    client = salt.client.LocalClient(__opts__["conf_file"])
    for info in client.cmd_iter("virtual:physical", "virt.full_info", expr_form="grain"):
        if not info:
            continue
        if not isinstance(info, dict):
            continue
        chunk = {}
        id_ = info.keys()[0]
        if hyper:
            if hyper != id_:
                continue
        if not isinstance(info[id_], dict):
            continue
        if not "ret" in info[id_]:
            continue
        chunk[id_] = info[id_]["ret"]
        ret.update(chunk)
        if not quiet:
            salt.output.display_output(chunk, "virt_query", __opts__)

    return ret
开发者ID:Barrybaby,项目名称:salt,代码行数:26,代码来源:virt.py


示例2: list_

def list_(host=None, quiet=False):
    '''
    List defined containers (running, stopped, and frozen) for the named
    (or all) host(s).

    .. code-block:: bash

        salt-run lxc.list [host=minion_id]
    '''

    tgt = host or '*'
    ret = {}
    client = salt.client.LocalClient(__opts__['conf_file'])
    for container_info in client.cmd_iter(tgt, 'lxc.list'):
        if not container_info:
            continue
        if not isinstance(container_info, dict):
            continue
        chunk = {}
        id_ = container_info.keys()[0]
        if host and host != id_:
            continue
        if not isinstance(container_info[id_], dict):
            continue
        if 'ret' not in container_info[id_]:
            continue
        if not isinstance(container_info[id_]['ret'], dict):
            continue
        chunk[id_] = container_info[id_]['ret']
        ret.update(chunk)
        if not quiet:
            salt.output.display_output(chunk, 'lxc_list', __opts__)

    return ret
开发者ID:Anbcorp,项目名称:salt,代码行数:34,代码来源:lxc.py


示例3: _do_names

def _do_names(names, fun, path=None):
    '''
    Invoke a function in the lxc module with no args

    path
        path to the container parent
        default: /var/lib/lxc (system default)

        .. versionadded:: Beryllium
    '''
    ret = {}
    hosts = find_guests(names, path=path)
    if not hosts:
        return False

    client = salt.client.get_local_client(__opts__['conf_file'])
    for host, sub_names in six.iteritems(hosts):
        cmds = []
        for name in sub_names:
            cmds.append(client.cmd_iter(
                    host,
                    'lxc.{0}'.format(fun),
                    [name],
                    kwarg={'path': path},
                    timeout=60))
        for cmd in cmds:
            data = next(cmd)
            data = data.get(host, {}).get('ret', None)
            if data:
                ret.update({host: data})
    return ret
开发者ID:dmyerscough,项目名称:salt,代码行数:31,代码来源:lxc.py


示例4: cmd_iter

def cmd_iter(tgt,
             fun,
             arg=(),
             timeout=None,
             expr_form='glob',
             ret='',
             kwarg=None,
             ssh=False,
             **kwargs):
    '''
    Assuming this minion is a master, execute a salt command

    CLI Example:

    .. code-block:: bash

        salt '*' saltutil.cmd
    '''
    if ssh:
        client = salt.client.SSHClient(
                os.path.dirname(__opts__['conf_file']))
    else:
        client = salt.client.LocalClient(
                os.path.dirname(__opts__['conf_file']))
    for ret in client.cmd_iter(
            tgt,
            fun,
            arg,
            timeout,
            expr_form,
            ret,
            kwarg,
            **kwargs):
        yield ret
开发者ID:Basis,项目名称:salt,代码行数:34,代码来源:saltutil.py


示例5: query

def query(hyper=None, quiet=False):
    """
    Query the virtual machines. When called without options all hypervisors
    are detected and a full query is returned. A single hypervisor can be
    passed in to specify an individual hypervisor to query.
    """
    ret = {}
    client = salt.client.get_local_client(__opts__["conf_file"])
    for info in client.cmd_iter("virtual:physical", "virt.full_info", expr_form="grain"):
        if not info:
            continue
        if not isinstance(info, dict):
            continue
        chunk = {}
        id_ = info.iterkeys().next()
        if hyper:
            if hyper != id_:
                continue
        if not isinstance(info[id_], dict):
            continue
        if "ret" not in info[id_]:
            continue
        if not isinstance(info[id_]["ret"], dict):
            continue
        chunk[id_] = info[id_]["ret"]
        ret.update(chunk)
        if not quiet:
            salt.output.display_output(chunk, "virt_query", __opts__)

    return ret
开发者ID:wikimedia,项目名称:operations-debs-salt,代码行数:30,代码来源:virt.py


示例6: pause

def pause(name):
    '''
    Pause the named VM
    '''
    ret = {}
    client = salt.client.get_local_client(__opts__['conf_file'])

    data = vm_info(name, quiet=True)
    if not data:
        __jid_event__.fire_event({'error': 'Failed to find VM {0} to pause'.format(name)}, 'progress')
        return 'fail'
    host = next(six.iterkeys(data))
    if data[host][name]['state'] == 'paused':
        __jid_event__.fire_event({'error': 'VM {0} is already paused'.format(name)}, 'progress')
        return 'bad state'
    try:
        cmd_ret = client.cmd_iter(
                host,
                'virt.pause',
                [name],
                timeout=600)
    except SaltClientError as client_error:
        return 'Virtual machine {0} could not be pasued: {1}'.format(name, client_error)
    for comp in cmd_ret:
        ret.update(comp)
    __jid_event__.fire_event({'message': 'Paused VM {0}'.format(name)}, 'progress')
    return 'good'
开发者ID:HowardMei,项目名称:saltstack,代码行数:27,代码来源:virt.py


示例7: _list_iter

def _list_iter(host=None, path=None):
    '''
    Return a generator iterating over hosts

    path
        path to the container parent
        default: /var/lib/lxc (system default)

        .. versionadded:: Beryllium
    '''
    tgt = host or '*'
    client = salt.client.get_local_client(__opts__['conf_file'])
    for container_info in client.cmd_iter(
        tgt, 'lxc.list', kwarg={'path': path}
    ):
        if not container_info:
            continue
        if not isinstance(container_info, dict):
            continue
        chunk = {}
        id_ = next(six.iterkeys(container_info))
        if host and host != id_:
            continue
        if not isinstance(container_info[id_], dict):
            continue
        if 'ret' not in container_info[id_]:
            continue
        if not isinstance(container_info[id_]['ret'], dict):
            continue
        chunk[id_] = container_info[id_]['ret']
        yield chunk
开发者ID:dmyerscough,项目名称:salt,代码行数:31,代码来源:lxc.py


示例8: purge

def purge(name, delete_key=True):
    '''
    Destroy the named vm
    '''
    ret = {}
    client = salt.client.get_local_client(__opts__['conf_file'])
    data = vm_info(name, quiet=True)
    if not data:
        __jid_event__.fire_event({'error': 'Failed to find vm {0} to purge'.format(name)}, 'progress')
        return 'fail'
    hyper = next(six.iterkeys(data))
    try:
        cmd_ret = client.cmd_iter(
                hyper,
                'virt.purge',
                [name, True],
                timeout=600)
    except SaltClientError as client_error:
        return 'Virtual machine {0} could not be purged: {1}'.format(name, client_error)

    for comp in cmd_ret:
        ret.update(comp)

    if delete_key:
        skey = salt.key.Key(__opts__)
        skey.delete_key(name)
    __jid_event__.fire_event({'message': 'Purged VM {0}'.format(name)}, 'progress')
    return 'good'
开发者ID:DaveQB,项目名称:salt,代码行数:28,代码来源:virt.py


示例9: force_off

def force_off(name):
    '''
    Force power down the named virtual machine
    '''
    ret = {}
    client = salt.client.get_local_client(__opts__['conf_file'])
    data = vm_info(name, quiet=True)
    if not data:
        print('Failed to find vm {0} to destroy'.format(name))
        return 'fail'
    hyper = next(six.iterkeys(data))
    if data[hyper][name]['state'] == 'shutdown':
        print('VM {0} is already shutdown'.format(name))
        return'bad state'
    try:
        cmd_ret = client.cmd_iter(
                hyper,
                'virt.destroy',
                [name],
                timeout=600)
    except SaltClientError as client_error:
        return 'Virtual machine {0} could not be forced off: {1}'.format(name, client_error)
    for comp in cmd_ret:
        ret.update(comp)
    __jid_event__.fire_event({'message': 'Powered off VM {0}'.format(name)}, 'progress')
    return 'good'
开发者ID:DaveQB,项目名称:salt,代码行数:26,代码来源:virt.py


示例10: create_zombies

def create_zombies(stack, n):
    """
    For the given stack, will randomly select `n` hosts and kill the
    salt-minion service that should already be running on the host.

    @param (stacks.models.Stack) stack - the stack we're targeting
    @param (int) n - the number of randomly selected hosts to zombify
    @returns (None)
    """

    # Random sampling of n hosts
    hosts = random.sample(stack.hosts.all(), n)
    if not hosts:
        return

    client = salt.client.LocalClient(
        settings.STACKDIO_CONFIG.salt_master_config
    )
    result = list(client.cmd_iter(
        [h.hostname for h in hosts],
        'service.stop',
        arg=('salt-minion',),
        expr_form='list'
    ))
    logger.info(result)
开发者ID:clarkperkins,项目名称:stackdio,代码行数:25,代码来源:utils.py


示例11: resume

def resume(name):
    '''
    Resume a paused vm
    '''
    ret = {}
    client = salt.client.get_local_client(__opts__['conf_file'])
    data = vm_info(name, quiet=True)
    if not data:
        __jid_event__.fire_event({'error': 'Failed to find VM {0} to pause'.format(name)}, 'progress')
        return 'not found'
    hyper = next(six.iterkeys(data))
    if data[hyper][name]['state'] != 'paused':
        __jid_event__.fire_event({'error': 'VM {0} is not paused'.format(name)}, 'progress')
        return 'bad state'
    try:
        cmd_ret = client.cmd_iter(
                hyper,
                'virt.resume',
                [name],
                timeout=600)
    except SaltClientError as client_error:
        return 'Virtual machine {0} could not be resumed: {1}'.format(name, client_error)
    for comp in cmd_ret:
        ret.update(comp)
    __jid_event__.fire_event({'message': 'Resumed VM {0}'.format(name)}, 'progress')
    return 'good'
开发者ID:DaveQB,项目名称:salt,代码行数:26,代码来源:virt.py


示例12: sync_all

def sync_all(stack):
    # Update status
    stack.log_history('Synchronizing salt systems on all hosts.', Activity.PROVISIONING)

    logger.info('Syncing all salt systems for stack: {0!r}'.format(stack))

    # Generate all the files before we sync
    stack.generate_orchestrate_file()
    stack.generate_global_orchestrate_file()

    target = [h.hostname for h in stack.get_hosts()]
    client = salt.client.LocalClient(settings.STACKDIO_CONFIG.salt_master_config)

    ret = client.cmd_iter(target, 'saltutil.sync_all', kwarg={'saltenv': 'base'}, expr_form='list')

    result = {}
    for res in ret:
        for host, data in res.items():
            result[host] = data

    for host, data in result.items():
        if 'retcode' not in data:
            logger.warning('Host {0} missing a retcode... assuming failure'.format(host))

        if data.get('retcode', 1) != 0:
            err_msg = six.text_type(data['ret'])
            raise StackTaskException('Error syncing salt data: {0!r}'.format(err_msg))

    stack.log_history('Finished synchronizing salt systems on all hosts.')
开发者ID:stackdio,项目名称:stackdio,代码行数:29,代码来源:tasks.py


示例13: ping

def ping(stack, activity, interval=5, max_failures=10):
    """
    Attempts to use salt's test.ping module to ping the entire stack
    and confirm that all hosts are reachable by salt.

    @stack_id: The id of the stack to ping. We will use salt's grain
               system to target the hosts with this stack id
    @interval: The looping interval, ie, the amount of time to sleep
               before the next iteration.
    @max_failures: Number of ping failures before giving up completely.
                   The timeout does not affect this parameter.
    @raises StackTaskException
    """
    stack.log_history('Attempting to ping all hosts.', activity)
    required_hosts = [h.hostname for h in stack.get_hosts()]

    client = salt.client.LocalClient(settings.STACKDIO_CONFIG.salt_master_config)

    # Execute until successful, failing after a few attempts
    failures = 0

    while True:
        ret = client.cmd_iter(required_hosts, 'test.ping', expr_form='list')

        result = {}
        for res in ret:
            for host, data in res.items():
                result[host] = data

        # check that we got a report back for all hosts
        pinged_hosts = set(result.keys())
        missing_hosts = set(required_hosts).difference(pinged_hosts)
        if missing_hosts:
            failures += 1
            logger.debug('The following hosts did not respond to '
                         'the ping request: {0}; Total failures: '
                         '{1}'.format(missing_hosts,
                                      failures))

        false_hosts = []
        for host, data in result.items():
            if data['ret'] is not True or data['retcode'] != 0:
                failures += 1
                false_hosts.append(host)

        if not missing_hosts and not false_hosts:
            # Successful ping.
            break

        if failures > max_failures:
            err_msg = 'Max failures ({0}) reached while pinging hosts.'.format(max_failures)
            raise StackTaskException(err_msg)

        time.sleep(interval)

    if false_hosts:
        err_msg = 'Unable to ping hosts: {0}'.format(', '.join(false_hosts))
        raise StackTaskException(err_msg)

    stack.log_history('All hosts pinged successfully.')
开发者ID:stackdio,项目名称:stackdio,代码行数:60,代码来源:tasks.py


示例14: query

def query(hyper=None, quiet=False):
    '''
    Query the virtual machines. When called without options all hypervisors
    are detected and a full query is returned. A single hypervisor can be
    passed in to specify an individual hypervisor to query.
    '''
    if quiet:
        log.warn('\'quiet\' is deprecated. Please migrate to --quiet')
    ret = {}
    client = salt.client.get_local_client(__opts__['conf_file'])
    try:
        for info in client.cmd_iter('virtual:physical',
                                    'virt.full_info', expr_form='grain'):
            if not info:
                continue
            if not isinstance(info, dict):
                continue
            chunk = {}
            id_ = next(info.iterkeys())
            if hyper:
                if hyper != id_:
                    continue
            if not isinstance(info[id_], dict):
                continue
            if 'ret' not in info[id_]:
                continue
            if not isinstance(info[id_]['ret'], dict):
                continue
            chunk[id_] = info[id_]['ret']
            ret.update(chunk)
            if not quiet:
                __jid_event__.fire_event({'data': chunk, 'outputter': 'virt_query'}, 'progress')
    except SaltClientError as client_error:
        print(client_error)
    return ret
开发者ID:DaveQB,项目名称:salt,代码行数:35,代码来源:virt.py


示例15: cmd

def cmd(tgt,
        fun,
        arg=(),
        timeout=None,
        expr_form='glob',
        ret='',
        kwarg=None,
        ssh=False,
        **kwargs):
    '''
    Assuming this minion is a master, execute a salt command

    CLI Example:

    .. code-block:: bash

        salt '*' saltutil.cmd
    '''
    if ssh:
        client = salt.client.SSHClient(__opts__['conf_file'])
    else:
        client = salt.client.LocalClient(__opts__['conf_file'])
    ret = {}
    for ret_comp in client.cmd_iter(
            tgt,
            fun,
            arg,
            timeout,
            expr_form,
            ret,
            kwarg,
            **kwargs):
        ret.update(ret_comp)
    return ret
开发者ID:Anbcorp,项目名称:salt,代码行数:34,代码来源:saltutil.py


示例16: _do

def _do(name, fun, path=None):
    '''
    Invoke a function in the lxc module with no args

    path
        path to the container parent
        default: /var/lib/lxc (system default)

        .. versionadded:: Beryllium
    '''
    host = find_guest(name, quiet=True, path=path)
    if not host:
        return False

    client = salt.client.get_local_client(__opts__['conf_file'])
    cmd_ret = client.cmd_iter(
            host,
            'lxc.{0}'.format(fun),
            [name],
            kwarg={'path': path},
            timeout=60)
    data = next(cmd_ret)
    data = data.get(host, {}).get('ret', None)
    if data:
        data = {host: data}
    return data
开发者ID:dmyerscough,项目名称:salt,代码行数:26,代码来源:lxc.py


示例17: start

def start(name):
    '''
    Start a named virtual machine
    '''
    ret = {}
    client = salt.client.get_local_client(__opts__['conf_file'])
    data = vm_info(name, quiet=True)
    if not data:
        __jid_event__.fire_event({'message': 'Failed to find vm {0} to start'.format(name)}, 'progress')
        return 'fail'
    hyper = next(six.iterkeys(data))
    if data[hyper][name]['state'] == 'running':
        print('VM {0} is already running'.format(name))
        return 'bad state'
    try:
        cmd_ret = client.cmd_iter(
                hyper,
                'virt.start',
                [name],
                timeout=600)
    except SaltClientError as client_error:
        return 'Virtual machine {0} not started: {1}'. format(name, client_error)
    for comp in cmd_ret:
        ret.update(comp)
    __jid_event__.fire_event({'message': 'Started VM {0}'.format(name)}, 'progress')
    return 'good'
开发者ID:DaveQB,项目名称:salt,代码行数:26,代码来源:virt.py


示例18: query

def query(hyper=None, quiet=False):
    '''
    Query the virtual machines. When called without options all hypervisors
    are detected and a full query is returned. A single hypervisor can be
    passed in to specify an individual hypervisor to query.
    '''
    ret = {}
    client = salt.client.get_local_client(__opts__['conf_file'])
    for info in client.cmd_iter('virtual:physical',
                                'virt.full_info', expr_form='grain'):
        if not info:
            continue
        if not isinstance(info, dict):
            continue
        chunk = {}
        id_ = info.keys()[0]
        if hyper:
            if hyper != id_:
                continue
        if not isinstance(info[id_], dict):
            continue
        if 'ret' not in info[id_]:
            continue
        if not isinstance(info[id_]['ret'], dict):
            continue
        chunk[id_] = info[id_]['ret']
        ret.update(chunk)
        if not quiet:
            salt.output.display_output(chunk, 'virt_query', __opts__)

    return ret
开发者ID:AccelerationNet,项目名称:salt,代码行数:31,代码来源:virt.py


示例19: list

def list(hyper=None, quiet=False):
    '''
    List the virtual machines on each hyper
    '''
    ret = {}
    client = salt.client.LocalClient(__opts__['conf_file'])
    for info in client.cmd_iter('virtual:physical',
                                'virt.vm_info', expr_form='grain'):
        if not info:
            continue
        if not isinstance(info, dict):
            continue
        chunk = {}
        id_ = info.keys()[0]
        if hyper:
            if hyper != id_:
                continue
        if not isinstance(info[id_], dict):
            continue
        if 'ret' not in info[id_]:
            continue
        if not isinstance(info[id_]['ret'], dict):
            continue
        data = {}
        for k, v in info[id_]['ret'].items():
            if v['state'] in data:
                data[v['state']].append(k)
            else:
                data[v['state']] = [k]
        chunk[id_] = data
        ret.update(chunk)
        if not quiet:
            salt.output.display_output(chunk, 'virt_list', __opts__)

    return ret
开发者ID:Anbcorp,项目名称:salt,代码行数:35,代码来源:virt.py


示例20: execution

def execution():
    '''
    Collect all the sys.doc output from each minion and return the aggregate

    CLI Example:

    .. code-block:: bash

        salt-run doc.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
开发者ID:bryson,项目名称:salt,代码行数:25,代码来源:doc.py



注:本文中的salt.client.cmd_iter函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python config.get_config_value函数代码示例发布时间:2022-05-27
下一篇:
Python client.cmd函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap