text
stringlengths
81
112k
Convert zfs bool to python bool def from_bool(value): ''' Convert zfs bool to python bool ''' if value in ['on', 'yes']: value = True elif value in ['off', 'no']: value = False elif value == 'none': value = None return value
Convert python bool to zfs on/off bool def to_bool(value): ''' Convert python bool to zfs on/off bool ''' value = from_bool(value) if isinstance(value, bool): value = 'on' if value else 'off' elif value is None: value = 'none' return value
Convert python to zfs yes/no value def to_bool_alt(value): ''' Convert python to zfs yes/no value ''' value = from_bool_alt(value) if isinstance(value, bool): value = 'yes' if value else 'no' elif value is None: value = 'none' return value
Convert zfs size (human readble) to python int (bytes) def from_size(value): ''' Convert zfs size (human readble) to python int (bytes) ''' match_size = re_zfs_size.match(str(value)) if match_size: v_unit = match_size.group(2).upper()[0] v_size = float(match_size.group(1)) v...
Convert python int (bytes) to zfs size NOTE: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/pyzfs/common/util.py#114 def to_size(value, convert_to_human=True): ''' Convert python int (bytes) to zfs size NOTE: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/pyzfs/common/util.p...
Decode zfs safe string (used for name, path, ...) def from_str(value): ''' Decode zfs safe string (used for name, path, ...) ''' if value == 'none': value = None if value: value = str(value) if value.startswith('"') and value.endswith('"'): value = value[1:-1] ...
Encode zfs safe string (used for name, path, ...) def to_str(value): ''' Encode zfs safe string (used for name, path, ...) ''' value = from_str(value) if value: value = value.replace('"', '\\"') if ' ' in value: value = '"' + value + '"' elif value is None: ...
Convert python value to zfs value def to_auto(name, value, source='auto', convert_to_human=True): ''' Convert python value to zfs value ''' return _auto('to', name, value, source, convert_to_human)
Pass an entire dictionary to from_auto .. note:: The key will be passed as the name def from_auto_dict(values, source='auto'): ''' Pass an entire dictionary to from_auto .. note:: The key will be passed as the name ''' for name, value in values.items(): values[name] =...
Pass an entire dictionary to to_auto .. note:: The key will be passed as the name def to_auto_dict(values, source='auto', convert_to_human=True): ''' Pass an entire dictionary to to_auto .. note:: The key will be passed as the name ''' for name, value in values.items(): ...
Build and properly escape a zpool command .. note:: Input is not considered safe and will be passed through to_auto(from_auto('input_here')), you do not need to do so your self first. def zpool_command(command, flags=None, opts=None, property_name=None, property_value=None, ...
Parse the result of a zpool/zfs command .. note:: Output on failure is rather predicatable. - retcode > 0 - each 'error' is a line on stderr - optional 'Usage:' block under those with hits We simple check those and return a OrderedDict were we set label = True|Fals...
Read the log file and return match whole string .. code-block:: yaml beacons: log: - file: <path> - tags: <tag>: regex: <pattern> .. note:: regex matching is based on the `re`_ module .. _re: https://docs.pyth...
Convert key/value to tree def key_value_to_tree(data): ''' Convert key/value to tree ''' tree = {} for flatkey, value in six.iteritems(data): t = tree keys = flatkey.split(__opts__['pepa_delimiter']) for i, key in enumerate(keys, 1): if i == len(keys): ...
Evaluate Pepa templates def ext_pillar(minion_id, pillar, resource, sequence, subkey=False, subkey_only=False): ''' Evaluate Pepa templates ''' roots = __opts__['pepa_roots'] # Default input inp = {} inp['default'] = 'default' inp['hostname'] = minion_id if 'environment' in pillar...
Validate Pepa templates def validate(output, resource): ''' Validate Pepa templates ''' try: import cerberus # pylint: disable=import-error except ImportError: log.critical('You need module cerberus in order to use validation') return roots = __opts__['pepa_roots'] ...
Return list of disk devices def disks(): ''' Return list of disk devices ''' if salt.utils.platform.is_freebsd(): return _freebsd_geom() elif salt.utils.platform.is_linux(): return _linux_disks() elif salt.utils.platform.is_windows(): return _windows_disks() else: ...
Return list of disk devices and work out if they are SSD or HDD. def _linux_disks(): ''' Return list of disk devices and work out if they are SSD or HDD. ''' ret = {'disks': [], 'SSDs': []} for entry in glob.glob('/sys/block/*/queue/rotational'): try: with salt.utils.files.fope...
Ensure that the VirtualBox Guest Additions are installed. Uses the CD, connected by VirtualBox. name The name has no functional value and is only used as a tracking reference. reboot : False Restart OS to complete installation. upgrade_os : False Upgrade OS (to ensure th...
Ensure that the VirtualBox Guest Additions are removed. Uses the CD, connected by VirtualBox. To connect VirtualBox Guest Additions via VirtualBox graphical interface press 'Host+D' ('Host' is usually 'Right Ctrl'). name The name has no functional value and is only used as a tracking r...
Grant access to auto-mounted shared folders to the users. User is specified by it's name. To grant access for several users use argument `users`. name Name of the user to grant access to auto-mounted shared folders to. users List of names of users to grant access to auto-mounted shared...
Perform a lightweight check to see if the master daemon is running Note, this will return an invalid success if the master crashed or was not shut down cleanly. def _is_master_running(self): ''' Perform a lightweight check to see if the master daemon is running Note, this will...
Execute the specified function in the specified client by passing the lowstate def run(self, low): ''' Execute the specified function in the specified client by passing the lowstate ''' # Eauth currently requires a running daemon and commands run through # this m...
Run :ref:`execution modules <all-salt.modules>` asynchronously Wraps :py:meth:`salt.client.LocalClient.run_job`. :return: job ID def local_async(self, *args, **kwargs): ''' Run :ref:`execution modules <all-salt.modules>` asynchronously Wraps :py:meth:`salt.client.LocalClient....
Run :ref:`execution modules <all-salt.modules>` synchronously See :py:meth:`salt.client.LocalClient.cmd` for all available parameters. Sends a command from the master to the targeted minions. This is the same interface that Salt's own CLI uses. Note the ``arg`` and ``kwarg`` pa...
Run :ref:`execution modules <all-salt.modules>` against subsets of minions .. versionadded:: 2016.3.0 Wraps :py:meth:`salt.client.LocalClient.cmd_subset` def local_subset(self, *args, **kwargs): ''' Run :ref:`execution modules <all-salt.modules>` against subsets of minions .....
Run :ref:`execution modules <all-salt.modules>` against batches of minions .. versionadded:: 0.8.4 Wraps :py:meth:`salt.client.LocalClient.cmd_batch` :return: Returns the result from the exeuction module for each batch of returns def local_batch(self, *args, **kwargs): ''...
Run salt-ssh commands synchronously Wraps :py:meth:`salt.client.ssh.client.SSHClient.cmd_sync`. :return: Returns the result from the salt-ssh command def ssh(self, *args, **kwargs): ''' Run salt-ssh commands synchronously Wraps :py:meth:`salt.client.ssh.client.SSHClient.cmd_s...
Run `runner modules <all-salt.runners>` synchronously Wraps :py:meth:`salt.runner.RunnerClient.cmd_sync`. Note that runner functions must be called using keyword arguments. Positional arguments are not supported. :return: Returns the result from the runner module def runner(self, fun...
Run `runner modules <all-salt.runners>` asynchronously Wraps :py:meth:`salt.runner.RunnerClient.cmd_async`. Note that runner functions must be called using keyword arguments. Positional arguments are not supported. :return: event data and a job ID for the executed function. def runne...
Run :ref:`wheel modules <all-salt.wheel>` synchronously Wraps :py:meth:`salt.wheel.WheelClient.master_call`. Note that wheel functions must be called using keyword arguments. Positional arguments are not supported. :return: Returns the result from the wheel module def wheel(self, fun...
Run :ref:`wheel modules <all-salt.wheel>` asynchronously Wraps :py:meth:`salt.wheel.WheelClient.master_call`. Note that wheel functions must be called using keyword arguments. Positional arguments are not supported. :return: Returns the result from the wheel module def wheel_async(se...
Pass in a raw string and load the json when it starts. This allows for a string to start with garbage and end with json but be cleanly loaded def find_json(raw): ''' Pass in a raw string and load the json when it starts. This allows for a string to start with garbage and end with json but be cleanly lo...
Import a json module, starting with the quick ones and going down the list) def import_json(): ''' Import a json module, starting with the quick ones and going down the list) ''' for fast_json in ('ujson', 'yajl', 'json'): try: mod = __import__(fast_json) log.trace('load...
.. versionadded:: 2018.3.0 Wraps json.loads and prevents a traceback in the event that a bytestring is passed to the function. (Python < 3.6 cannot load bytestrings) You can pass an alternate json module (loaded via import_json() above) using the _json_module argument) def loads(s, **kwargs): '''...
.. versionadded:: 2018.3.0 Wraps json.dump, and assumes that ensure_ascii is False (unless explicitly passed as True) for unicode compatibility. Note that setting it to True will mess up any unicode characters, as they will be dumped as the string literal version of the unicode code point. On Pyth...
User Metadata def _user_mdata(mdata_list=None, mdata_get=None): ''' User Metadata ''' grains = {} if not mdata_list: mdata_list = salt.utils.path.which('mdata-list') if not mdata_get: mdata_get = salt.utils.path.which('mdata-get') if not mdata_list or not mdata_get: ...
SDC Metadata specified by there specs https://eng.joyent.com/mdata/datadict.html def _sdc_mdata(mdata_list=None, mdata_get=None): ''' SDC Metadata specified by there specs https://eng.joyent.com/mdata/datadict.html ''' grains = {} sdc_text_keys = [ 'uuid', 'server_uuid', ...
Grains for backwards compatibility Remove this function in Neon def _legacy_grains(grains): ''' Grains for backwards compatibility Remove this function in Neon ''' # parse legacy sdc grains if 'mdata' in grains and 'sdc' in grains['mdata']: if 'server_uuid' not in grains['mdata']['s...
Provide grains from the SmartOS metadata def mdata(): ''' Provide grains from the SmartOS metadata ''' grains = {} mdata_list = salt.utils.path.which('mdata-list') mdata_get = salt.utils.path.which('mdata-get') grains = salt.utils.dictupdate.update(grains, _user_mdata(mdata_list, mdata_get...
Check xdg locations for config files def xdg_config_dir(): ''' Check xdg locations for config files ''' xdg_config = os.getenv('XDG_CONFIG_HOME', os.path.expanduser('~/.config')) xdg_config_directory = os.path.join(xdg_config, 'salt') return xdg_config_directory
Ensure the SNS topic exists. name Name of the SNS topic. subscriptions List of SNS subscriptions. Each subscription is a dictionary with a protocol and endpoint key: .. code-block:: yaml subscriptions: - Protocol: https Endpoint: https:/...
Ensure the named sns topic is deleted. name Name of the SNS topic. unsubscribe If True, unsubscribe all subcriptions to the SNS topic before deleting the SNS topic region Region to connect to. key Secret key to be used. keyid Access key to be used...
Start the saltnado! def start(): ''' Start the saltnado! ''' mod_opts = __opts__.get(__virtualname__, {}) if 'num_processes' not in mod_opts: mod_opts['num_processes'] = 1 if mod_opts['num_processes'] > 1 and mod_opts.get('debug', False) is True: raise Exception(( ...
Checks if the named user and group are present on the minion def _check_user(user, group): ''' Checks if the named user and group are present on the minion ''' err = '' if user: uid = __salt__['file.user_to_uid'](user) if uid == '': err += 'User {0} is not available '.fo...
Performs basic sanity checks on a relative path. Requires POSIX-compatible paths (i.e. the kind obtained through cp.list_master or other such calls). Ensures that the path does not contain directory transversal, and that it does not exceed a stated maximum depth (if specified). def _is_valid_relpath(...
Converts a path from the form received via salt master to the OS's native path format. def _salt_to_os_path(path): ''' Converts a path from the form received via salt master to the OS's native path format. ''' return os.path.normpath(path.replace(posixpath.sep, os.path.sep))
Generate the list of files managed by a recurse state def _gen_recurse_managed_files( name, source, keep_symlinks=False, include_pat=None, exclude_pat=None, maxdepth=None, include_empty=False, **kwargs): ''' Generate the list of files managed by a...
Generate the list of files that need to be kept when a dir based function like directory or recurse has a clean. def _gen_keep_files(name, require, walk_d=None): ''' Generate the list of files that need to be kept when a dir based function like directory or recurse has a clean. ''' def _is_chil...
Compile a list of valid keep files (and directories). Used by _clean_dir() def _find_keep_files(root, keep): ''' Compile a list of valid keep files (and directories). Used by _clean_dir() ''' real_keep = set() real_keep.add(root) if isinstance(keep, list): for fn_ in keep: ...
Clean out all of the files and directories in a directory (root) while preserving the files in a list (keep) and part of exclude_pat def _clean_dir(root, keep, exclude_pat): ''' Clean out all of the files and directories in a directory (root) while preserving the files in a list (keep) and part of excl...
Check what changes need to be made on a directory def _check_directory(name, user=None, group=None, recurse=False, mode=None, file_mode=None, clean=False, require=False, ...
Check what changes need to be made on a directory def _check_directory_win(name, win_owner=None, win_perms=None, win_deny_perms=None, win_inheritance=None, win_perms_reset=None): ''' Che...
Check the changes in directory metadata def _check_dir_meta(name, user, group, mode, follow_symlinks=False): ''' Check the changes in directory metadata ''' try: stats = __salt__['file.stats'](name, None, follow_sym...
Check to see if a file needs to be updated or created def _check_touch(name, atime, mtime): ''' Check to see if a file needs to be updated or created ''' ret = { 'result': None, 'comment': '', 'changes': {'new': name}, } if not os.path.exists(name): ret['comment'...
Check if the symlink ownership matches the specified user and group def _check_symlink_ownership(path, user, group, win_owner): ''' Check if the symlink ownership matches the specified user and group ''' cur_user, cur_group = _get_symlink_ownership(path) if salt.utils.platform.is_windows(): ...
Set the ownership of a symlink and return a boolean indicating success/failure def _set_symlink_ownership(path, user, group, win_owner): ''' Set the ownership of a symlink and return a boolean indicating success/failure ''' if salt.utils.platform.is_windows(): try: salt.util...
Check the symlink function def _symlink_check(name, target, force, user, group, win_owner): ''' Check the symlink function ''' changes = {} if not os.path.exists(name) and not __salt__['file.is_link'](name): changes['new'] = name return None, 'Symlink {0} to {1} is set for creation'...
Silly little function to give us a standard tuple list for sources and source_hashes def _unify_sources_and_hashes(source=None, source_hash=None, sources=None, source_hashes=None): ''' Silly little function to give us a standard tuple list for sources and source_hashes ...
Iterate a list of sources and process them as templates. Returns a list of 'chunks' containing the rendered templates. def _get_template_texts(source_list=None, template='jinja', defaults=None, context=None, **kwargs): ...
ensure ``arg`` is a list of strings def _validate_str_list(arg): ''' ensure ``arg`` is a list of strings ''' if isinstance(arg, six.binary_type): ret = [salt.utils.stringutils.to_unicode(arg)] elif isinstance(arg, six.string_types): ret = [arg] elif isinstance(arg, Iterable) and...
Set the ownership of a shortcut and return a boolean indicating success/failure def _set_shortcut_ownership(path, user): ''' Set the ownership of a shortcut and return a boolean indicating success/failure ''' try: __salt__['file.lchown'](path, user) except OSError: pass ...
Check the shortcut function def _shortcut_check(name, target, arguments, working_dir, description, icon_location, force, user): ''' Check the shortcut function ''' ...
Helper function for creating directories when the ``makedirs`` option is set to ``True``. Handles Unix and Windows based systems .. versionadded:: 2017.7.8 Args: name (str): The directory path to create user (str): The linux user to own the directory group (str): The linux group to...
Create a symbolic link (symlink, soft link) If the file already exists and is a symlink pointing to any location other than the specified target, the symlink will be replaced. If the symlink is a regular file or directory then the state will return False. If the regular file or directory is desired to ...
Make sure that the named file or directory is absent. If it exists, it will be deleted. This will work to reverse any of the functions in the file state module. If a directory is supplied, it will be recursively deleted. name The path which should be deleted def absent(name, **kwargs): ...
Remove unwanted files based on specific criteria. Multiple criteria are OR’d together, so a file that is too large but is not old enough will still get tidied. If neither age nor size is given all files which match a pattern in matches will be removed. name The directory tree that should b...
Verify that the named file or directory is present or exists. Ensures pre-requisites outside of Salt's purview (e.g., keytabs, private keys, etc.) have been previously satisfied before deployment. This function does not create the file if it doesn't exist, it will return an error. name ...
r''' Manage a given file, this function allows for a file to be downloaded from the salt master and potentially run through a templating system. name The location of the file to manage, as an absolute path. source The source file to download to the minion, this source file can be ...
Converse *recurse* definition to a set of strings. Raises TypeError or ValueError when *recurse* has wrong structure. def _get_recurse_set(recurse): ''' Converse *recurse* definition to a set of strings. Raises TypeError or ValueError when *recurse* has wrong structure. ''' if not recurse: ...
Walk the directory tree under root up till reaching max_depth. With max_depth=None (default), do not limit depth. def _depth_limited_walk(top, max_depth=None): ''' Walk the directory tree under root up till reaching max_depth. With max_depth=None (default), do not limit depth. ''' for root, dir...
r''' Ensure that a named directory is present and has the right perms name The location to create or manage a directory, as an absolute path user The user to own the directory; this defaults to the user salt is running as on the minion group The group ownership set for...
Recurse through a subdirectory on the master and copy said subdirectory over to the specified path. name The directory to set the recursion in source The source directory, this directory is located on the salt master file server and is specified with the salt:// protocol. If the di...
Apply retention scheduling to backup storage directory. .. versionadded:: 2016.11.0 :param name: The filesystem path to the directory containing backups to be managed. :param retain: Delete the backups, except for the ones we want to keep. The N below should be an integer but may ...
Line-based editing of a file. .. versionadded:: 2015.8.0 :param name: Filesystem path to the file to be edited. :param content: Content of the line. Allowed to be empty if mode=delete. :param match: Match the target line for an action by a fragment of a string or regu...
r''' Maintain an edit in a file. .. versionadded:: 0.17.0 name Filesystem path to the file to be edited. If a symlink is specified, it will be resolved to its target. pattern A regular expression, to be matched using Python's :py:func:`re.search`. .. note:: ...
Key/Value based editing of a file. .. versionadded:: Neon This function differs from ``file.replace`` in that it is able to search for keys, followed by a customizable separator, and replace the value with the given value. Should the value be the same as the one already in the file, no changes wil...
Maintain an edit in a file in a zone delimited by two line markers .. versionadded:: 2014.1.0 .. versionchanged:: 2017.7.5,2018.3.1 ``append_newline`` argument added. Additionally, to improve idempotence, if the string represented by ``marker_end`` is found in the middle of the line, th...
Comment out specified lines in a file. name The full path to the file to be edited regex A regular expression used to find the lines that are to be commented; this pattern will be wrapped in parenthesis and will move any preceding/trailing ``^`` or ``$`` characters outside the p...
Uncomment specified commented lines in a file name The full path to the file to be edited regex A regular expression used to find the lines that are to be uncommented. This regex should not include the comment character. A leading ``^`` character will be stripped for convenience...
Ensure that some text appears at the end of a file. The text will not be appended if it already exists in the file. A single string of text or a list of strings may be appended. name The location of the file to append to. text The text to be appended, which can be a single string or a...
Ensure that a patch has been applied to the specified file or directory .. versionchanged:: 2019.2.0 The ``hash`` and ``dry_run_first`` options are now ignored, as the logic which determines whether or not the patch has already been applied no longer requires them. Additionally, this state ...
Replicate the 'nix "touch" command to create a new empty file or update the atime and mtime of an existing file. Note that if you just want to create a file and don't care about atime or mtime, you should use ``file.managed`` instead, as it is more feature-complete. (Just leave out the ``source``/``te...
If the file defined by the ``source`` option exists on the minion, copy it to the named path. The file will not be overwritten if it already exists, unless the ``force`` option is set to ``True``. .. note:: This state only copies files from one location on a minion to another location on th...
If the source file exists on the system, rename it to the named file. The named file will not be overwritten if it already exists unless the force option is set to True. name The location of the file to rename to source The location of the file to move to the location specified with na...
Prepare accumulator which can be used in template in file.managed state. Accumulator dictionary becomes available in template. It can also be used in file.blockreplace. name Accumulator name filename Filename which would receive this accumulator (see file.managed state document...
Serializes dataset and store it into managed file. Useful for sharing simple configuration files. name The location of the file to create dataset The dataset that will be serialized dataset_pillar Operates like ``dataset``, but draws from a value stored in pillar, usin...
Create a special file similar to the 'nix mknod command. The supported device types are ``p`` (fifo pipe), ``c`` (character device), and ``b`` (block device). Provide the major and minor numbers when specifying a character device or block device. A fifo pipe does not require this information. The comman...
Execute the check_cmd logic. Return a result dict if ``check_cmd`` succeeds (check_cmd == 0) otherwise return True def mod_run_check_cmd(cmd, filename, **check_cmd_opts): ''' Execute the check_cmd logic. Return a result dict if ``check_cmd`` succeeds (check_cmd == 0) otherwise return True ...
Decode an encoded file and write it to disk .. versionadded:: 2016.3.0 name Path of the file to be written. encoded_data The encoded file. Either this option or ``contents_pillar`` must be specified. contents_pillar A Pillar path to the encoded file. Uses the same path ...
Create a Windows shortcut If the file already exists and is a shortcut pointing to any location other than the specified target, the shortcut will be replaced. If it is a regular file or directory then the state will return False. If the regular file or directory is desired to be replaced with a shortc...
.. versionadded:: 2017.7.3 Ensures that a file is saved to the minion's cache. This state is primarily invoked by other states to ensure that we do not re-download a source file if we do not need to. name The URL of the file to be cached. To cache a file from an environment other than ...
.. versionadded:: 2017.7.3 Ensures that a file is not present in the minion's cache, deleting it if found. This state is primarily invoked by other states to ensure that a fresh copy is fetched. name The URL of the file to be removed from cache. To remove a file from cache in an enviro...
Return the rendered script def __render_script(path, vm_=None, opts=None, minion=''): ''' Return the rendered script ''' log.info('Rendering deploy script: %s', path) try: with salt.utils.files.fopen(path, 'r') as fp_: template = Template(salt.utils.stringutils.to_unicode(fp_.re...
Return a dictionary with gateway options. The result is used to provide arguments to __ssh_gateway_arguments method. def __ssh_gateway_config_dict(gateway): ''' Return a dictionary with gateway options. The result is used to provide arguments to __ssh_gateway_arguments method. ''' extended_kwar...
Return ProxyCommand configuration string for ssh/scp command. All gateway options should not include quotes (' or "). To support future user configuration, please make sure to update the dictionary from __ssh_gateway_config_dict and get_ssh_gateway_config (ec2.py) def __ssh_gateway_arguments(kwargs): ...
Return the script as a string for the specific os def os_script(os_, vm_=None, opts=None, minion=''): ''' Return the script as a string for the specific os ''' if minion: minion = salt_config_to_yaml(minion) if os.path.isabs(os_): # The user provided an absolute path to the deploy ...
Generate Salt minion keys and return them as PEM file strings def gen_keys(keysize=2048): ''' Generate Salt minion keys and return them as PEM file strings ''' # Mandate that keys are at least 2048 in size if keysize < 2048: keysize = 2048 tdir = tempfile.mkdtemp() salt.crypt.gen_k...
If the master config was available then we will have a pki_dir key in the opts directory, this method places the pub key in the accepted keys dir and removes it from the unaccepted keys dir if that is the case. def accept_key(pki_dir, pub, id_): ''' If the master config was available then we will have ...
This method removes a specified key from the accepted keys dir def remove_key(pki_dir, id_): ''' This method removes a specified key from the accepted keys dir ''' key = os.path.join(pki_dir, 'minions', id_) if os.path.isfile(key): os.remove(key) log.debug('Deleted \'%s\'', key)