INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Unmounts ZFS file systems name : string name of the filesystem, you can use None to unmount all mounted filesystems. force : boolean forcefully unmount the file system, even if it is currently in use. .. warning:: Using ``-a`` for the name parameter will probably break your system...
def unmount(name, **kwargs): ''' Unmounts ZFS file systems name : string name of the filesystem, you can use None to unmount all mounted filesystems. force : boolean forcefully unmount the file system, even if it is currently in use. .. warning:: Using ``-a`` for the name ...
Clears the specified property prop : string name of property name : string name of the filesystem, volume, or snapshot recursive : boolean recursively inherit the given property for all children. revert : boolean revert the property to the received value if one exists; o...
def inherit(prop, name, **kwargs): ''' Clears the specified property prop : string name of property name : string name of the filesystem, volume, or snapshot recursive : boolean recursively inherit the given property for all children. revert : boolean revert the ...
Display the difference between a snapshot of a given filesystem and another snapshot of that filesystem from a later time or the current contents of the filesystem. name_a : string name of snapshot name_b : string (optional) name of snapshot or filesystem show_changetime : boolean ...
def diff(name_a, name_b=None, **kwargs): ''' Display the difference between a snapshot of a given filesystem and another snapshot of that filesystem from a later time or the current contents of the filesystem. name_a : string name of snapshot name_b : string (optional) name of s...
Roll back the given dataset to a previous snapshot. name : string name of snapshot recursive : boolean destroy any snapshots and bookmarks more recent than the one specified. recursive_all : boolean destroy any more recent snapshots and bookmarks, as well as any clon...
def rollback(name, **kwargs): ''' Roll back the given dataset to a previous snapshot. name : string name of snapshot recursive : boolean destroy any snapshots and bookmarks more recent than the one specified. recursive_all : boolean destroy any more recent snapshots ...
Creates a clone of the given snapshot. name_a : string name of snapshot name_b : string name of filesystem or volume create_parent : boolean creates all the non-existing parent datasets. any property specified on the command line using the -o option is ignored. propertie...
def clone(name_a, name_b, **kwargs): ''' Creates a clone of the given snapshot. name_a : string name of snapshot name_b : string name of filesystem or volume create_parent : boolean creates all the non-existing parent datasets. any property specified on the command l...
Promotes a clone file system to no longer be dependent on its "origin" snapshot. .. note:: This makes it possible to destroy the file system that the clone was created from. The clone parent-child dependency relationship is reversed, so that the origin file system becomes a clone of th...
def promote(name): ''' Promotes a clone file system to no longer be dependent on its "origin" snapshot. .. note:: This makes it possible to destroy the file system that the clone was created from. The clone parent-child dependency relationship is reversed, so that the origin fi...
Lists all existing user references for the given snapshot or snapshots. snapshot : string name of snapshot recursive : boolean lists the holds that are set on the named descendent snapshots also. .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zfs.h...
def holds(snapshot, **kwargs): ''' Lists all existing user references for the given snapshot or snapshots. snapshot : string name of snapshot recursive : boolean lists the holds that are set on the named descendent snapshots also. .. versionadded:: 2016.3.0 CLI Example: ....
Creates a bookmark of the given snapshot .. note:: Bookmarks mark the point in time when the snapshot was created, and can be used as the incremental source for a zfs send command. This feature must be enabled to be used. See zpool-features(5) for details on ZFS feature flags and ...
def bookmark(snapshot, bookmark): ''' Creates a bookmark of the given snapshot .. note:: Bookmarks mark the point in time when the snapshot was created, and can be used as the incremental source for a zfs send command. This feature must be enabled to be used. See zpool-features(5)...
Adds a single reference, named with the tag argument, to the specified snapshot or snapshots. .. note:: Each snapshot has its own tag namespace, and tags must be unique within that space. If a hold exists on a snapshot, attempts to destroy that snapshot by using the zfs destroy comman...
def hold(tag, *snapshot, **kwargs): ''' Adds a single reference, named with the tag argument, to the specified snapshot or snapshots. .. note:: Each snapshot has its own tag namespace, and tags must be unique within that space. If a hold exists on a snapshot, attempts to destroy that ...
Creates snapshots with the given names. snapshot : string name of snapshot(s) recursive : boolean recursively create snapshots of all descendent datasets. properties : dict additional zfs properties (-o) .. note:: ZFS properties can be specified at the time of creation...
def snapshot(*snapshot, **kwargs): ''' Creates snapshots with the given names. snapshot : string name of snapshot(s) recursive : boolean recursively create snapshots of all descendent datasets. properties : dict additional zfs properties (-o) .. note:: ZFS prop...
Sets the property or list of properties to the given value(s) for each dataset. dataset : string name of snapshot(s), filesystem(s), or volume(s) properties : string additional zfs properties pairs .. note:: properties are passed as key-value pairs. e.g. compression=o...
def set(*dataset, **kwargs): ''' Sets the property or list of properties to the given value(s) for each dataset. dataset : string name of snapshot(s), filesystem(s), or volume(s) properties : string additional zfs properties pairs .. note:: properties are passed as key-val...
Displays properties for the given datasets. dataset : string name of snapshot(s), filesystem(s), or volume(s) properties : string comma-separated list of properties to list, defaults to all recursive : boolean recursively list children depth : int recursively list childr...
def get(*dataset, **kwargs): ''' Displays properties for the given datasets. dataset : string name of snapshot(s), filesystem(s), or volume(s) properties : string comma-separated list of properties to list, defaults to all recursive : boolean recursively list children de...
Helper function to raise a warning, by default, a ``DeprecationWarning``, until the provided ``version``, after which, a ``RuntimeError`` will be raised to remind the developers to remove the warning because the target version has been reached. :param version: The version info or name after which the w...
def warn_until(version, message, category=DeprecationWarning, stacklevel=None, _version_info_=None, _dont_call_warnings=False): ''' Helper function to raise a warning, by default, a ``DeprecationWarning``, until the provided ``versio...
Helper function to raise a warning (by default, a ``DeprecationWarning``) when unhandled keyword arguments are passed to function, until the provided ``version_info``, after which, a ``RuntimeError`` will be raised to remind the developers to remove the ``**kwargs`` because the target version has been r...
def kwargs_warn_until(kwargs, version, category=DeprecationWarning, stacklevel=None, _version_info_=None, _dont_call_warnings=False): ''' Helper function to raise a warning (by default, a ``DeprecationW...
Compares two version strings using salt.utils.versions.LooseVersion. This is a fallback for providers which don't have a version comparison utility built into them. Return -1 if version1 < version2, 0 if version1 == version2, and 1 if version1 > version2. Return None if there was a problem making the c...
def version_cmp(pkg1, pkg2, ignore_epoch=False): ''' Compares two version strings using salt.utils.versions.LooseVersion. This is a fallback for providers which don't have a version comparison utility built into them. Return -1 if version1 < version2, 0 if version1 == version2, and 1 if version1 > ...
Compares two version numbers. Accepts a custom function to perform the cmp-style version comparison, otherwise uses version_cmp().
def compare(ver1='', oper='==', ver2='', cmp_func=None, ignore_epoch=False): ''' Compares two version numbers. Accepts a custom function to perform the cmp-style version comparison, otherwise uses version_cmp(). ''' cmp_map = {'<': (-1,), '<=': (-1, 0), '==': (0,), '>=': (0, 1), '>': ...
Checks for the version of various required boto libs in one central location. Most boto states and modules rely on a single version of the boto, boto3, or botocore libs. However, some require newer versions of any of these dependencies. This function allows the module to pass in a version to override the de...
def check_boto_reqs(boto_ver=None, boto3_ver=None, botocore_ver=None, check_boto=True, check_boto3=True): ''' Checks for the version of various required boto libs in one central location. Most boto states and modules rely on a s...
.. versionadded:: 2017.11.0 Create target group if not present. name (string) - The name of the target group. protocol (string) - The protocol to use for routing traffic to the targets port (int) - The port on which the targets receive traffic. This port is used unless ...
def create_target_group(name, protocol, port, vpc_id, region=None, key=None, keyid=None, profile=None, health_check_protocol='HTTP', health_check_port='traffic-port', health_check_path='/', health_check_interval_seconds=30, ...
Delete target group. name (string) - The Amazon Resource Name (ARN) of the resource. returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash check-target: boto_elb2.delete_targets_group: - name: myALB - protocol...
def delete_target_group(name, region=None, key=None, keyid=None, profile=None): ''' Delete target group. name (string) - The Amazon Resource Name (ARN) of the resource. returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash check-target...
.. versionadded:: 2017.7.0 Add targets to an Application Load Balancer target group. This state will not remove targets. name The ARN of the Application Load Balancer Target Group to add targets to. targets A list of target IDs or a string of a single target that this target group should ...
def targets_registered(name, targets, region=None, key=None, keyid=None, profile=None, **kwargs): ''' .. versionadded:: 2017.7.0 Add targets to an Application Load Balancer target group. This state will not remove targets. name The ARN of the Application Load Balancer Ta...
Show all employees for this company. CLI Example: salt myminion bamboohr.list_employees By default, the return data will be keyed by ID. However, it can be ordered by any other field. Keep in mind that if the field that is chosen contains duplicate values (i.e., location is used, for a compan...
def list_employees(order_by='id'): ''' Show all employees for this company. CLI Example: salt myminion bamboohr.list_employees By default, the return data will be keyed by ID. However, it can be ordered by any other field. Keep in mind that if the field that is chosen contains duplica...
Show all employees for this company. CLI Example: salt myminion bamboohr.show_employee 1138 By default, the fields normally returned from bamboohr.list_employees are returned. These fields are: - canUploadPhoto - department - displayName - firstName - id ...
def show_employee(emp_id, fields=None): ''' Show all employees for this company. CLI Example: salt myminion bamboohr.show_employee 1138 By default, the fields normally returned from bamboohr.list_employees are returned. These fields are: - canUploadPhoto - department ...
Update one or more items for this employee. Specifying an empty value will clear it for that employee. CLI Examples: salt myminion bamboohr.update_employee 1138 nickname Curly salt myminion bamboohr.update_employee 1138 nickname '' salt myminion bamboohr.update_employee 1138 items='{"n...
def update_employee(emp_id, key=None, value=None, items=None): ''' Update one or more items for this employee. Specifying an empty value will clear it for that employee. CLI Examples: salt myminion bamboohr.update_employee 1138 nickname Curly salt myminion bamboohr.update_employee 1138...
Show all users for this company. CLI Example: salt myminion bamboohr.list_users By default, the return data will be keyed by ID. However, it can be ordered by any other field. Keep in mind that if the field that is chosen contains duplicate values (i.e., location is used, for a company which ...
def list_users(order_by='id'): ''' Show all users for this company. CLI Example: salt myminion bamboohr.list_users By default, the return data will be keyed by ID. However, it can be ordered by any other field. Keep in mind that if the field that is chosen contains duplicate values (i...
Show all meta data fields for this company. CLI Example: salt myminion bamboohr.list_meta_fields
def list_meta_fields(): ''' Show all meta data fields for this company. CLI Example: salt myminion bamboohr.list_meta_fields ''' ret = {} status, result = _query(action='meta', command='fields') root = ET.fromstring(result) fields = root.getchildren() for field in fields: ...
Make a web call to BambooHR The password can be any random text, so we chose Salty text.
def _query(action=None, command=None, args=None, method='GET', data=None): ''' Make a web call to BambooHR The password can be any random text, so we chose Salty text. ''' subdomain = __opts__.get('bamboohr', {}).get('subdomain', None) path = 'https:/...
Get an sqlite3 connection, and initialize the package database if necessary
def init(): ''' Get an sqlite3 connection, and initialize the package database if necessary ''' if not os.path.exists(__opts__['spm_cache_dir']): log.debug('Creating SPM cache directory at %s', __opts__['spm_db']) os.makedirs(__opts__['spm_cache_dir']) if not os.path.exists(__opts__...
List info for a package
def info(package, conn=None): ''' List info for a package ''' close = False if conn is None: close = True conn = init() fields = ( 'package', 'version', 'release', 'installed', 'os', 'os_family', 'dependencies', 'os...
List files for an installed package
def list_packages(conn=None): ''' List files for an installed package ''' close = False if conn is None: close = True conn = init() ret = [] data = conn.execute('SELECT package FROM packages') for pkg in data.fetchall(): ret.append(pkg) if close: con...
List files for an installed package
def list_files(package, conn=None): ''' List files for an installed package ''' close = False if conn is None: close = True conn = init() data = conn.execute('SELECT package FROM packages WHERE package=?', (package, )) if not data.fetchone(): if close: co...
Register a package in the package database
def register_pkg(name, formula_def, conn=None): ''' Register a package in the package database ''' close = False if conn is None: close = True conn = init() conn.execute('INSERT INTO packages VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', ( name, formula_def['version...
Register a file in the package database
def register_file(name, member, path, digest='', conn=None): ''' Register a file in the package database ''' close = False if conn is None: close = True conn = init() conn.execute('INSERT INTO files VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', ( name, '{0}/{1}'....
Unregister a file from the package database
def unregister_file(path, pkg=None, conn=None): # pylint: disable=W0612 ''' Unregister a file from the package database ''' close = False if conn is None: close = True conn = init() conn.execute('DELETE FROM files WHERE path=?', (path, )) if close: conn.close()
This function gets called when the proxy starts up.
def init(opts): ''' This function gets called when the proxy starts up. ''' if 'host' not in opts['proxy']: log.critical('No \'host\' key found in pillar for this proxy.') return False if 'username' not in opts['proxy']: log.critical('No \'username\' key found in pillar for t...
Sends a post command to the device and returns the decoded data.
def call(payload, apply_changes=False): ''' Sends a post command to the device and returns the decoded data. ''' session, cookies, csrf_token = logon() response = _post_request(session, payload, cookies, csrf_token) if apply_changes: apply_payload = {"jsonrpc": "2.0", ...
Logs into the bluecoat_sslv device and returns the session cookies.
def logon(): ''' Logs into the bluecoat_sslv device and returns the session cookies. ''' session = requests.session() payload = {"jsonrpc": "2.0", "id": "ID0", "method": "login", "params": [DETAILS['username'], DETAILS['password'], DETAILS['auth'], True] ...
Closes the session with the device.
def logout(session, cookies, csrf_token): ''' Closes the session with the device. ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "logout", "params": [] } session.post(DETAILS['url'], data=json.dumps(payload), ...
Get the grains from the proxied device
def grains(): ''' Get the grains from the proxied device ''' if not DETAILS.get('grains_cache', {}): DETAILS['grains_cache'] = GRAINS_CACHE try: DETAILS['grains_cache'] = _get_grain_information() except salt.exceptions.CommandExecutionError: pass e...
Returns true if the device is reachable, else false.
def ping(): ''' Returns true if the device is reachable, else false. ''' try: session, cookies, csrf_token = logon() logout(session, cookies, csrf_token) except salt.exceptions.CommandExecutionError: return False except Exception as err: log.debug(err) ret...
.. versionadded:: 2015.5.0 .. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Execute a single command via the salt-ssh subsystem and return all routines at once A wrapper around the :py:meth:`SSHClient.cmd...
def cmd(tgt, fun, arg=(), timeout=None, tgt_type='glob', kwarg=None): ''' .. versionadded:: 2015.5.0 .. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Execute a singl...
Mint a new token using the config option hash_type and store tdata with 'token' attribute set to the token. This module uses the hash of random 512 bytes as a token. :param opts: Salt master config options :param tdata: Token data to be stored with 'token' attirbute of this dict set to the token. :...
def mk_token(opts, tdata): ''' Mint a new token using the config option hash_type and store tdata with 'token' attribute set to the token. This module uses the hash of random 512 bytes as a token. :param opts: Salt master config options :param tdata: Token data to be stored with 'token' attirbu...
Fetch the token data from the store. :param opts: Salt master config options :param tok: Token value to get :returns: Token data if successful. Empty dict if failed.
def get_token(opts, tok): ''' Fetch the token data from the store. :param opts: Salt master config options :param tok: Token value to get :returns: Token data if successful. Empty dict if failed. ''' t_path = os.path.join(opts['token_dir'], tok) if not os.path.isfile(t_path): re...
Remove token from the store. :param opts: Salt master config options :param tok: Token to remove :returns: Empty dict if successful. None if failed.
def rm_token(opts, tok): ''' Remove token from the store. :param opts: Salt master config options :param tok: Token to remove :returns: Empty dict if successful. None if failed. ''' t_path = os.path.join(opts['token_dir'], tok) try: os.remove(t_path) return {} except...
List all tokens in the store. :param opts: Salt master config options :returns: List of dicts (tokens)
def list_tokens(opts): ''' List all tokens in the store. :param opts: Salt master config options :returns: List of dicts (tokens) ''' ret = [] for (dirpath, dirnames, filenames) in salt.utils.path.os_walk(opts['token_dir']): for token in filenames: ret.append(token) ...
Equivalent to os.path.islink()
def islink(path): ''' Equivalent to os.path.islink() ''' if six.PY3 or not salt.utils.platform.is_windows(): return os.path.islink(path) if not HAS_WIN32FILE: log.error('Cannot check if %s is a link, missing required modules', path) if not _is_reparse_point(path): retur...
Equivalent to os.readlink()
def readlink(path): ''' Equivalent to os.readlink() ''' if six.PY3 or not salt.utils.platform.is_windows(): return os.readlink(path) if not HAS_WIN32FILE: log.error('Cannot read %s, missing required modules', path) reparse_data = _get_reparse_data(path) if not reparse_data...
Returns True if path is a reparse point; False otherwise.
def _is_reparse_point(path): ''' Returns True if path is a reparse point; False otherwise. ''' result = win32file.GetFileAttributesW(path) if result == -1: return False return True if result & 0x400 else False
Retrieves the reparse point data structure for the given path. If the path is not a reparse point, None is returned. See http://msdn.microsoft.com/en-us/library/ff552012.aspx for details on the REPARSE_DATA_BUFFER structure returned.
def _get_reparse_data(path): ''' Retrieves the reparse point data structure for the given path. If the path is not a reparse point, None is returned. See http://msdn.microsoft.com/en-us/library/ff552012.aspx for details on the REPARSE_DATA_BUFFER structure returned. ''' # ensure paths are ...
Scan over some possible executables and return the first one that is found
def which_bin(exes): ''' Scan over some possible executables and return the first one that is found ''' if not isinstance(exes, Iterable): return None for exe in exes: path = which(exe) if not path: continue return path return None
This functions tries to solve some issues when joining multiple absolute paths on both *nix and windows platforms. See tests/unit/utils/path_join_test.py for some examples on what's being talked about here. The "use_posixpath" kwarg can be be used to force joining using poxixpath, which is useful ...
def join(*parts, **kwargs): ''' This functions tries to solve some issues when joining multiple absolute paths on both *nix and windows platforms. See tests/unit/utils/path_join_test.py for some examples on what's being talked about here. The "use_posixpath" kwarg can be be used to force joini...
Remove illegal path characters for windows
def sanitize_win_path(winpath): ''' Remove illegal path characters for windows ''' intab = '<>:|?*' if isinstance(winpath, six.text_type): winpath = winpath.translate(dict((ord(c), '_') for c in intab)) elif isinstance(winpath, six.string_types): outtab = '_' * len(intab) ...
r''' .. versionadded:: 2017.7.3 Checks that the path is safe for modification by Salt. For example, you wouldn't want to have salt delete the contents of ``C:\Windows``. The following directories are considered unsafe: - C:\, D:\, E:\, etc. - \ - C:\Windows Args: path (str): ...
def safe_path(path, allow_path=None): r''' .. versionadded:: 2017.7.3 Checks that the path is safe for modification by Salt. For example, you wouldn't want to have salt delete the contents of ``C:\Windows``. The following directories are considered unsafe: - C:\, D:\, E:\, etc. - \ - C...
This is a helper than ensures that all paths returned from os.walk are unicode.
def os_walk(top, *args, **kwargs): ''' This is a helper than ensures that all paths returned from os.walk are unicode. ''' if six.PY2 and salt.utils.platform.is_windows(): top_query = top else: top_query = salt.utils.stringutils.to_str(top) for item in os.walk(top_query, *arg...
Used to parse emerge output to provide meaningful output when emerge fails
def _process_emerge_err(stdout, stderr): ''' Used to parse emerge output to provide meaningful output when emerge fails ''' ret = {} rexp = re.compile(r'^[<>=][^ ]+/[^ ]+ [^\n]+', re.M) slot_conflicts = re.compile(r'^[^ \n]+/[^ ]+:[^ ]', re.M).findall(stderr) if slot_conflicts: ret[...
.. versionadded:: 0.17.0 Returns a dict containing the following information for each specified package: 1. A key ``found``, which will be a boolean value denoting if a match was found in the package database. 2. If ``found`` is ``False``, then a second key called ``suggestions`` will be...
def check_db(*names, **kwargs): ''' .. versionadded:: 0.17.0 Returns a dict containing the following information for each specified package: 1. A key ``found``, which will be a boolean value denoting if a match was found in the package database. 2. If ``found`` is ``False``, then a seco...
List all available package upgrades. refresh Whether or not to sync the portage tree before checking for upgrades. backtrack Specifies an integer number of times to backtrack if dependency calculation fails due to a conflict or an unsatisfied dependency (default: ´3´). ...
def list_upgrades(refresh=True, backtrack=3, **kwargs): # pylint: disable=W0613 ''' List all available package upgrades. refresh Whether or not to sync the portage tree before checking for upgrades. backtrack Specifies an integer number of times to backtrack if dependency calc...
Returns a list containing the matches for a given package name from the portage tree. Note that the specific version of the package will not be provided for packages that have several versions in the portage tree, but rather the name of the package (i.e. "dev-python/paramiko").
def porttree_matches(name): ''' Returns a list containing the matches for a given package name from the portage tree. Note that the specific version of the package will not be provided for packages that have several versions in the portage tree, but rather the name of the package (i.e. "dev-python/p...
List the packages currently installed in a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs
def list_pkgs(versions_as_list=False, **kwargs): ''' List the packages currently installed in a dict:: {'<package_name>': '<version>'} CLI Example: .. code-block:: bash salt '*' pkg.list_pkgs ''' versions_as_list = salt.utils.data.is_true(versions_as_list) # not yet imple...
Update the portage tree using the first available method from the following list: - emaint sync - eix-sync - emerge-webrsync - emerge --sync To prevent the portage tree from being synced within one day of the previous sync, add the following pillar data for this minion: .. code-block:...
def refresh_db(**kwargs): ''' Update the portage tree using the first available method from the following list: - emaint sync - eix-sync - emerge-webrsync - emerge --sync To prevent the portage tree from being synced within one day of the previous sync, add the following pillar dat...
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any emerge commands spawned by Sa...
def install(name=None, refresh=False, pkgs=None, sources=None, slot=None, fromrepo=None, uses=None, binhost=None, **kwargs): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=20...
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any emerge commands spawned by Sa...
def update(pkg, slot=None, fromrepo=None, refresh=False, binhost=None, **kwargs): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's cont...
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any emerge commands spawned by Sa...
def remove(name=None, slot=None, fromrepo=None, pkgs=None, **kwargs): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. T...
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. This is done to keep systemd from killing any emerge commands spawned by Sa...
def purge(name=None, slot=None, fromrepo=None, pkgs=None, **kwargs): ''' .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 On minions running systemd>=205, `systemd-run(1)`_ is now used to isolate commands which modify installed packages from the ``salt-minion`` daemon's control group. Th...
Portage has a function to remove unused dependencies. If a package is provided, it will only removed the package if no other package depends on it. name The name of the package to be cleaned. slot Restrict the remove to a specific slot. Ignored if ``name`` is None. fromrepo ...
def depclean(name=None, slot=None, fromrepo=None, pkgs=None): ''' Portage has a function to remove unused dependencies. If a package is provided, it will only removed the package if no other package depends on it. name The name of the package to be cleaned. slot Restrict the re...
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem making the comparison. CLI Example: .. code-block:: bash salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
def version_cmp(pkg1, pkg2, **kwargs): ''' Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem making the comparison. CLI Example: .. code-block:: bash salt '*' pkg.version_cmp '0.2.4-0' '0.2....
Check if the installed package already has the given requirements. CLI Example: .. code-block:: bash salt '*' pkg.check_extra_requirements 'sys-devel/gcc' '~>4.1.2:4.1::gentoo[nls,fortran]'
def check_extra_requirements(pkgname, pkgver): ''' Check if the installed package already has the given requirements. CLI Example: .. code-block:: bash salt '*' pkg.check_extra_requirements 'sys-devel/gcc' '~>4.1.2:4.1::gentoo[nls,fortran]' ''' keyword = None match = re.match('^(...
Install a p12 certificate file into the macOS keychain name The certificate to install password The password for the certificate being installed formatted in the way described for openssl command in the PASS PHRASE ARGUMENTS section keychain The keychain to install the cer...
def installed(name, password, keychain="/Library/Keychains/System.keychain", **kwargs): ''' Install a p12 certificate file into the macOS keychain name The certificate to install password The password for the certificate being installed formatted in the way described for openss...
Uninstall a p12 certificate file from the macOS keychain name The certificate to uninstall, this can be a path for a .p12 or the friendly name password The password for the certificate being installed formatted in the way described for openssl command in the PASS PHRASE ARGUMEN...
def uninstalled(name, password, keychain="/Library/Keychains/System.keychain", keychain_password=None): ''' Uninstall a p12 certificate file from the macOS keychain name The certificate to uninstall, this can be a path for a .p12 or the friendly name password The password for t...
Set the default keychain to use name The chain in which to use as the default domain The domain to use valid values are user|system|common|dynamic, the default is user user The user to run as
def default_keychain(name, domain="user", user=None): ''' Set the default keychain to use name The chain in which to use as the default domain The domain to use valid values are user|system|common|dynamic, the default is user user The user to run as ''' ret = {'na...
Grab the opts dict of the master config by trying to import Salt
def bootstrap_app(): ''' Grab the opts dict of the master config by trying to import Salt ''' from salt.netapi.rest_cherrypy import app import salt.config __opts__ = salt.config.client_config( os.environ.get('SALT_MASTER_CONFIG', '/etc/salt/master')) return app.get_app(__opts__)
Returns a WSGI application function. If you supply the WSGI app and config it will use that, otherwise it will try to obtain them from a local Salt installation
def get_application(*args): ''' Returns a WSGI application function. If you supply the WSGI app and config it will use that, otherwise it will try to obtain them from a local Salt installation ''' opts_tuple = args def wsgi_app(environ, start_response): root, _, conf = opts_tuple or...
Return a sqlite3 database connection
def _get_conn(ret=None): ''' Return a sqlite3 database connection ''' # Possible todo: support detect_types, isolation_level, check_same_thread, # factory, cached_statements. Do we really need to though? _options = _get_options(ret) database = _options.get('database') timeout = _options....
Insert minion return data into the sqlite3 database
def returner(ret): ''' Insert minion return data into the sqlite3 database ''' log.debug('sqlite3 returner <returner> called with data: %s', ret) conn = _get_conn(ret) cur = conn.cursor() sql = '''INSERT INTO salt_returns (fun, jid, id, fun_args, date, full_ret, success) ...
Save the load to the specified jid
def save_load(jid, load, minions=None): ''' Save the load to the specified jid ''' log.debug('sqlite3 returner <save_load> called jid: %s load: %s', jid, load) conn = _get_conn(ret=None) cur = conn.cursor() sql = '''INSERT INTO jids (jid, load) VALUES (:jid, :load)''' cur.execute(sql, ...
Return the load from a specified jid
def get_load(jid): ''' Return the load from a specified jid ''' log.debug('sqlite3 returner <get_load> called jid: %s', jid) conn = _get_conn(ret=None) cur = conn.cursor() sql = '''SELECT load FROM jids WHERE jid = :jid''' cur.execute(sql, {'jid': jid}) data = cur.fet...
Return the information returned from a specified jid
def get_jid(jid): ''' Return the information returned from a specified jid ''' log.debug('sqlite3 returner <get_jid> called jid: %s', jid) conn = _get_conn(ret=None) cur = conn.cursor() sql = '''SELECT id, full_ret FROM salt_returns WHERE jid = :jid''' cur.execute(sql, {'...
Return a dict of the last function called for all minions
def get_fun(fun): ''' Return a dict of the last function called for all minions ''' log.debug('sqlite3 returner <get_fun> called fun: %s', fun) conn = _get_conn(ret=None) cur = conn.cursor() sql = '''SELECT s.id, s.full_ret, s.jid FROM salt_returns s JOIN ( SELECT MAX...
Return a list of minions
def get_minions(): ''' Return a list of minions ''' log.debug('sqlite3 returner <get_minions> called') conn = _get_conn(ret=None) cur = conn.cursor() sql = '''SELECT DISTINCT id FROM salt_returns''' cur.execute(sql) data = cur.fetchall() ret = [] for minion in data: r...
Ensure that we don't try to operate on worktrees in git < 2.5.0.
def _check_worktree_support(failhard=True): ''' Ensure that we don't try to operate on worktrees in git < 2.5.0. ''' git_version = version(versioninfo=False) if _LooseVersion(git_version) < _LooseVersion('2.5.0'): if failhard: raise CommandExecutionError( 'Worktre...
Common code for config.get_* functions, builds and runs the git CLI command and returns the result dict for the calling function to parse.
def _config_getter(get_opt, key, value_regex=None, cwd=None, user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' Common code fo...
Expand home directory
def _expand_path(cwd, user): ''' Expand home directory ''' try: to_expand = '~' + user if user else '~' except TypeError: # Users should never be numeric but if we don't account for this then # we're going to get a traceback if someone passes this invalid input. to_ex...
Check every part of path for executable permission
def _path_is_executable_others(path): ''' Check every part of path for executable permission ''' prevpath = None while path and path != prevpath: try: if not os.stat(path).st_mode & stat.S_IXOTH: return False except OSError: return False ...
Common code to inspect opts and split them if necessary
def _format_opts(opts): ''' Common code to inspect opts and split them if necessary ''' if opts is None: return [] elif isinstance(opts, list): new_opts = [] for item in opts: if isinstance(item, six.string_types): new_opts.append(item) ...
Do a version check and make sure that the installed version of git can support git -c
def _format_git_opts(opts): ''' Do a version check and make sure that the installed version of git can support git -c ''' if opts: version_ = version(versioninfo=False) if _LooseVersion(version_) < _LooseVersion('1.7.2'): raise SaltInvocationError( 'git_op...
Windows only: search for Git's bundled ssh.exe in known locations
def _find_ssh_exe(): ''' Windows only: search for Git's bundled ssh.exe in known locations ''' # Known locations for Git's ssh.exe in Windows globmasks = [os.path.join(os.getenv('SystemDrive'), os.sep, 'Program Files*', 'Git', 'usr', 'bin', ...
simple, throw an exception with the error message on an error return code. this function may be moved to the command module, spliced with 'cmd.run_all', and used as an alternative to 'cmd.run_all'. Some commands don't return proper retcodes, so this can't replace 'cmd.run_all'.
def _git_run(command, cwd=None, user=None, password=None, identity=None, ignore_retcode=False, failhard=True, redirect_stderr=False, saltenv='base', output_encoding=None, **kwargs): ''' simple, throw an exception with the error message on an error return code. this function may be...
Use git rev-parse to return the top level of a repo
def _get_toplevel(path, user=None, password=None, output_encoding=None): ''' Use git rev-parse to return the top level of a repo ''' return _git_run( ['git', 'rev-parse', '--show-toplevel'], cwd=path, user=user, password=password, output_encoding=output_encoding)[...
Helper to retrieve git config options
def _git_config(cwd, user, password, output_encoding=None): ''' Helper to retrieve git config options ''' contextkey = 'git.config.' + cwd if contextkey not in __context__: git_dir = rev_parse(cwd, opts=['--git-dir'], user=user, ...
Based on whether global or local config is desired, return a list of CLI args to include in the git config command.
def _which_git_config(global_, cwd, user, password, output_encoding=None): ''' Based on whether global or local config is desired, return a list of CLI args to include in the git config command. ''' if global_: return ['--global'] version_ = _LooseVersion(version(versioninfo=False)) ...
.. versionchanged:: 2015.8.0 The ``--verbose`` command line argument is now implied Interface to `git-add(1)`_ cwd The path to the git checkout filename The location of the file/directory to add, relative to ``cwd`` opts Any additional options to add to the command li...
def add(cwd, filename, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' .. versionchanged:: 2015.8.0 The ``--verbose`` command line argument is now implied Interface to `git-add(1)`_ cwd ...
.. versionchanged:: 2015.8.0 Returns ``True`` if successful, raises an error if not. Interface to `git-archive(1)`_, exports a tarball/zip file of the repository cwd The path to be archived .. note:: ``git archive`` permits a partial archive to be created. Thus, this ...
def archive(cwd, output, rev='HEAD', prefix=None, git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' .. versionchanged:: 2015.8.0 Returns ``True`` if...
Interface to `git-branch(1)`_ cwd The path to the git checkout name Name of the branch on which to operate. If not specified, the current branch will be assumed. opts Any additional options to add to the command line, in a single string .. note:: To cr...
def branch(cwd, name=None, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' Interface to `git-branch(1)`_ cwd The path to the git checkout name Name of the branc...
Interface to `git-checkout(1)`_ cwd The path to the git checkout opts Any additional options to add to the command line, in a single string .. note:: On the Salt CLI, if the opts are preceded with a dash, it is necessary to precede them with ``opts=`` (as in th...
def checkout(cwd, rev=None, force=False, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None): ''' Interface to `git-checkout(1)`_ cwd The path to the git c...
Interface to `git-clone(1)`_ cwd Location of git clone .. versionchanged:: 2015.8.0 If ``name`` is passed, then the clone will be made *within* this directory. url The URL of the repository to be cloned .. versionchanged:: 2015.8.0 Argument...
def clone(cwd, url=None, # Remove default value once 'repository' arg is removed name=None, opts='', git_opts='', user=None, password=None, identity=None, https_user=None, https_pass=None, ignore_retcode=False, ...
Interface to `git-commit(1)`_ cwd The path to the git checkout message Commit message opts Any additional options to add to the command line, in a single string. These opts will be added to the end of the git command being run. .. note:: On the Salt CL...
def commit(cwd, message, opts='', git_opts='', user=None, password=None, filename=None, ignore_retcode=False, output_encoding=None): ''' Interface to `git-commit(1)`_ cwd The path to the git checkout messag...
Get the value of a key in the git configuration file key The name of the configuration key to get .. versionchanged:: 2015.8.0 Argument renamed from ``setting_name`` to ``key`` cwd The path to the git checkout .. versionchanged:: 2015.8.0 Now optional ...
def config_get(key, cwd=None, user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' Get the value of a key in the git configuration file key The name of the configuration key to ...
r''' .. versionadded:: 2015.8.0 Get the value of a key or keys in the git configuration file using regexes for more flexible matching. The return data is a dictionary mapping keys to lists of values matching the ``value_regex``. If no values match, an empty dictionary will be returned. key ...
def config_get_regexp(key, value_regex=None, cwd=None, user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): r''' .. versionadded::...
.. versionadded:: 2015.8.0 Unset a key in the git configuration file cwd The path to the git checkout. Must be an absolute path, or the word ``global`` to indicate that a global key should be unset. key The name of the configuration key to unset value_regex Regular ex...
def config_unset(key, value_regex=None, cwd=None, user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' .. versionadded:: 2015.8.0 Unset a key in the git con...
.. versionchanged:: 2015.8.0 Return the value(s) of the key being set Set a key in the git configuration file cwd The path to the git checkout. Must be an absolute path, or the word ``global`` to indicate that a global key should be set. .. versionchanged:: 2014.7.0 ...
def config_set(key, value=None, multivar=None, cwd=None, user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' .. versionchanged:: 2015.8.0 Return the va...
Returns the current branch name of a local checkout. If HEAD is detached, return the SHA1 of the revision which is currently checked out. cwd The path to the git checkout user User under which to run the git command. By default, the command is run by the user under which the minion...
def current_branch(cwd, user=None, password=None, ignore_retcode=False, output_encoding=None): ''' Returns the current branch name of a local checkout. If HEAD is detached, return the SHA1 of the revision which is currently checked ...