INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Update the repo to a given revision. Using clean passes - C to the hg up
def _update_repo(ret, name, target, clean, user, identity, rev, opts, update_head): ''' Update the repo to a given revision. Using clean passes -C to the hg up ''' log.debug('target %s is found, "hg pull && hg up is probably required"', target) current_rev = __salt__['hg.revision'](target, user=use...
Check if a ZFS filesystem or volume or snapshot exists.
def exists(name, **kwargs): ''' Check if a ZFS filesystem or volume or snapshot exists. name : string name of dataset type : string also check if dataset is of a certain type, valid choices are: filesystem, snapshot, volume, bookmark, or all. .. versionadded:: 2015.5.0 ...
Create a ZFS File System.
def create(name, **kwargs): ''' Create a ZFS File System. name : string name of dataset or volume volume_size : string if specified, a zvol will be created instead of a dataset sparse : boolean create sparse volume create_parent : boolean creates all the non-exis...
Destroy a ZFS File System.
def destroy(name, **kwargs): ''' Destroy a ZFS File System. name : string name of dataset, volume, or snapshot force : boolean force an unmount of any file systems using the unmount -f command. recursive : boolean recursively destroy all children. (-r) recursive_all : bo...
Rename or Relocate a ZFS File System.
def rename(name, new_name, **kwargs): ''' Rename or Relocate a ZFS File System. name : string name of dataset, volume, or snapshot new_name : string new name of dataset, volume, or snapshot force : boolean force unmount any filesystems that need to be unmounted in the proces...
Return a list of all datasets or a specified dataset on the system and the values of their used available referenced and mountpoint properties.
def list_(name=None, **kwargs): ''' Return a list of all datasets or a specified dataset on the system and the values of their used, available, referenced, and mountpoint properties. name : string name of dataset, volume, or snapshot recursive : boolean recursively list children ...
List mounted zfs filesystems
def list_mount(): ''' List mounted zfs filesystems .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt '*' zfs.list_mount ''' ## List mounted filesystem res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='mount', ),...
Mounts ZFS file systems
def mount(name=None, **kwargs): ''' Mounts ZFS file systems name : string name of the filesystem, having this set to None will mount all filesystems. (this is the default) overlay : boolean perform an overlay mount. options : string optional comma-separated list of mount opt...
Unmounts ZFS file systems
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
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.
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.
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.
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.
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...
Creates a bookmark of the given snapshot
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)...
Lists all existing user references for the given snapshot or snapshots.
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: ....
Adds a single reference named with the tag argument to the specified snapshot or snapshots.
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.
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.
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.
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.
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 reached. This function is used to ...
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 comparison.
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 default minimum r...
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
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.
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
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.
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.
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.
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.
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.
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
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.
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.
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.
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.
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.
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.
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 ...
Python clone of/ usr/ bin/ which
def which(exe=None): ''' Python clone of /usr/bin/which ''' if not exe: log.error('No executable was passed to be searched by salt.utils.path.which()') return None ## define some utilities (we use closures here because our predecessor used them) def is_executable_common(path): ...
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.
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
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
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...
Utility function to get upgradable packages
def _get_upgradable(backtrack=3): ''' Utility function to get upgradable packages Sample return data: { 'pkgname': '1.2.3-45', ... } ''' cmd = ['emerge', '--ask', 'n', '--backtrack', '{0}'.format(backtrack), '--pretend', '--update', '--new...
List all available package upgrades.
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::
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:
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 Salt when the salt - min...
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 Salt when the salt - min...
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 Salt when the salt - min...
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 Salt when the salt - min...
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.
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.
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.
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
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
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
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.
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
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 ...