How to use the salt.utils function in salt

To help you get started, we’ve selected a few salt examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github saltstack / salt / tests / multimaster / beacons / test_inotify.py View on Github external
wait=1,
                            tag='salt/beacon/minion/status',
                            match_type='startswith',
                            )
                if sub_event is None:
                    sub_event = sub_master_listener.get_event(
                            full=True,
                            wait=1,
                            tag='salt/beacon/minion/status',
                            match_type='startswith',
                            )
                if event and sub_event:
                    break
            log.debug('Status events received: %s, %s', event, sub_event)

            with salt.utils.files.fopen(file_path, 'w') as f:
                pass

            start = time.time()
            # Now in successful case this test will get results at most in 2 loop intervals.
            # Waiting for 2 loops intervals + some seconds to the hardware stupidity.
            stop_at = start + self.mm_minion_opts['loop_interval'] * 2 + 60
            event = sub_event = None
            while True:
                if time.time() > stop_at:
                    break
                if not event:
                    event = master_listener.get_event(
                            full=True,
                            wait=1,
                            tag='salt/beacon/minion/inotify/' + self.tmpdir,
                            match_type='startswith',
github saltstack / salt / tests / support / gitfs.py View on Github external
self.run_function(
                'git.push',
                [self.admin_repo],
                remote='origin',
                ref=branch,
                user=user,
            )

        with salt.utils.files.fopen(
                os.path.join(self.admin_repo, 'top.sls'), 'w') as fp_:
            fp_.write(textwrap.dedent('''\
            base:
              '*':
                - foo
            '''))
        with salt.utils.files.fopen(
                os.path.join(self.admin_repo, 'foo.sls'), 'w') as fp_:
            fp_.write(textwrap.dedent('''\
            branch: master
            mylist:
              - master
            mydict:
              master: True
              nested_list:
                - master
              nested_dict:
                master: True
            '''))
        # Add another file to be referenced using git_pillar_includes
        with salt.utils.files.fopen(
                os.path.join(self.admin_repo, 'bar.sls'), 'w') as fp_:
            fp_.write('included_pillar: True\n')
github saltstack / salt / salt / modules / dnsmasq.py View on Github external
def _parse_file(filename):
    '''
    Generic function for parsing dnsmasq files, including includes
    '''
    fileopts = {}
    with salt.utils.fopen(filename, 'r') as fp_:
        for line in fp_:
            if not line.strip():
                continue
            if line.startswith('#'):
                continue
            if '=' in line:
                comps = line.split('=')
                if comps[0] in fileopts:
                    if isinstance(fileopts[comps[0]], str):
                        temp = fileopts[comps[0]]
                        fileopts[comps[0]] = [temp]
                    fileopts[comps[0]].append(comps[1].strip())
                else:
                    fileopts[comps[0]] = comps[1].strip()
            else:
                if not 'unparsed' in fileopts:
github saltstack / salt / salt / client / ssh / __init__.py View on Github external
def __arg_comps(self):
        '''
        Return the function name and the arg list
        '''
        fun = self.argv[0] if self.argv else ''
        parsed = salt.utils.args.parse_input(
            self.argv[1:],
            condition=False,
            no_parse=self.opts.get('no_parse', []))
        args = parsed[0]
        kws = parsed[1]
        return fun, args, kws
github saltstack / salt / salt / modules / win_pkg.py View on Github external
minion: `salt-call -l debug pkg.refresh saltenv=base`

    .. warning::
        When calling this command from a state using `module.run` be sure to
        pass `failhard: False`. Otherwise the state will report failure if it
        encounters a bad software definition file.

    CLI Example:

    .. code-block:: bash

        salt '*' pkg.refresh_db
        salt '*' pkg.refresh_db saltenv=base
    '''
    # Remove rtag file to keep multiple refreshes from happening in pkg states
    salt.utils.pkg.clear_rtag(__opts__)
    saltenv = kwargs.pop('saltenv', 'base')
    verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
    failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
    __context__.pop('winrepo.data', None)
    repo_details = _get_repo_details(saltenv)

    log.debug(
        'Refreshing pkg metadata db for saltenv \'%s\' (age of existing '
        'metadata is %s)',
        saltenv, datetime.timedelta(seconds=repo_details.winrepo_age)
    )

    # Clear minion repo-ng cache see #35342 discussion
    log.info('Removing all *.sls files under \'%s\'', repo_details.local_dest)
    failed = []
    for root, _, files in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
github saltstack / salt / salt / client / ssh / __init__.py View on Github external
if self.mine:
                result = wrapper[mine_fun](*self.args, **self.kwargs)
            else:
                result = self.wfuncs[self.fun](*self.args, **self.kwargs)
        except TypeError as exc:
            result = 'TypeError encountered executing {0}: {1}'.format(self.fun, exc)
            log.error(result, exc_info_on_loglevel=logging.DEBUG)
            retcode = 1
        except Exception as exc:
            result = 'An Exception occurred while executing {0}: {1}'.format(self.fun, exc)
            log.error(result, exc_info_on_loglevel=logging.DEBUG)
            retcode = 1
        # Mimic the json data-structure that "salt-call --local" will
        # emit (as seen in ssh_py_shim.py)
        if isinstance(result, dict) and 'local' in result:
            ret = salt.utils.json.dumps({'local': result['local']})
        else:
            ret = salt.utils.json.dumps({'local': {'return': result}})
        return ret, retcode
github latenighttales / alcali / docker / saltconfig / salt / _returners / alcali.py View on Github external
sql = """SELECT * FROM (
                     SELECT DISTINCT `jid` ,`load` FROM `jids`
                     {0}
                     ORDER BY `jid` DESC limit {1}
                     ) `tmp`
                 ORDER BY `jid`;"""
        where = """WHERE `load` NOT LIKE '%"fun": "saltutil.find_job"%' """

        cur.execute(sql.format(where if filter_find_job else "", count))
        data = cur.fetchall()
        ret = []
        for jid in data:
            ret.append(
                salt.utils.jid.format_jid_instance_ext(
                    jid[0], salt.utils.json.loads(jid[1])
                )
            )
        return ret
github saltstack / salt / salt / modules / postfix.py View on Github external
def _parse_main(path=MAIN_CF):
    '''
    Parse files in the style of main.cf. This is not just a "name = value" file;
    there are other rules:

    * Comments start with #
    * Any whitespace at the beginning of a line denotes that that line is a
        continuation from the previous line.
    * The whitespace rule applies to comments.
    * Keys defined in the file may be referred to as variables further down in
        the file.
    '''
    with salt.utils.fopen(path, 'r') as fh_:
        full_conf = fh_.read()

    # Condense the file based on line continuations, but keep order, comments
    # and whitespace
    conf_list = []
    for line in full_conf.splitlines():
        if not line.strip():
            conf_list.append(line)
            continue
        if re.match(SWWS, line):
            if not conf_list:
                # This should only happen at the top of the file
                conf_list.append(line)
                continue
            if not isinstance(conf_list[-1], str):
                conf_list[-1] = ''
github saltstack / salt / salt / transport / tcp.py View on Github external
import urllib.parse as urlparse
# pylint: enable=import-error,no-name-in-module

# Import third party libs
import msgpack
try:
    from M2Crypto import RSA
    HAS_M2 = True
except ImportError:
    HAS_M2 = False
    try:
        from Cryptodome.Cipher import PKCS1_OAEP
    except ImportError:
        from Crypto.Cipher import PKCS1_OAEP

if six.PY3 and salt.utils.platform.is_windows():
    USE_LOAD_BALANCER = True
else:
    USE_LOAD_BALANCER = False

if USE_LOAD_BALANCER:
    import threading
    import multiprocessing
    import tornado.util
    from salt.utils.process import SignalHandlingMultiprocessingProcess

log = logging.getLogger(__name__)


def _set_tcp_keepalive(sock, opts):
    '''
    Ensure that TCP keepalives are set for the socket.
github saltstack / salt / salt / cli / support / intfunc.py View on Github external
'''
    Add all files in the tree. If the "path" is a file,
    only that file will be added.

    :param path: File or directory
    :return:
    '''
    if not path:
        out.error('Path not defined', ident=2)
    else:
        # The filehandler needs to be explicitly passed here, so PyLint needs to accept that.
        # pylint: disable=W8470
        if os.path.isfile(path):
            filename = os.path.basename(path)
            try:
                file_ref = salt.utils.files.fopen(path)  # pylint: disable=W
                out.put('Add {}'.format(filename), indent=2)
                collector.add(filename)
                collector.link(title=path, path=file_ref)
            except Exception as err:
                out.error(err, ident=4)
        # pylint: enable=W8470
        else:
            for fname in os.listdir(path):
                fname = os.path.join(path, fname)
                filetree(collector, fname)