INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Ensure a Linux ACL list is present
def list_present(name, acl_type, acl_names=None, perms='', recurse=False, force=False): ''' Ensure a Linux ACL list is present Takes a list of acl names and add them to the given path name The acl path acl_type The type of the acl is used for it can be 'user' or 'group' acl_n...
Ensure a Linux ACL list does not exist
def list_absent(name, acl_type, acl_names=None, recurse=False): ''' Ensure a Linux ACL list does not exist Takes a list of acl names and remove them from the given path name The acl path acl_type The type of the acl is used for, it can be 'user' or 'group' acl_names T...
Helper function to retrieve objtype from pillars if objname is string_types used for SupportedLoginProviders and OpenIdConnectProviderARNs.
def _get_object(objname, objtype): ''' Helper function to retrieve objtype from pillars if objname is string_types, used for SupportedLoginProviders and OpenIdConnectProviderARNs. ''' ret = None if objname is None: return ret if isinstance(objname, string_types): if objn...
Helper function to set the Roles to the identity pool
def _role_present(ret, IdentityPoolId, AuthenticatedRole, UnauthenticatedRole, conn_params): ''' Helper function to set the Roles to the identity pool ''' r = __salt__['boto_cognitoidentity.get_identity_pool_roles'](IdentityPoolName='', Id...
Ensure Cognito Identity Pool exists.
def pool_present(name, IdentityPoolName, AuthenticatedRole, AllowUnauthenticatedIdentities=False, UnauthenticatedRole=None, SupportedLoginProviders=None, DeveloperProviderName=None, OpenIdConnectProvid...
Ensure cognito identity pool with passed properties is absent.
def pool_absent(name, IdentityPoolName, RemoveAllMatched=False, region=None, key=None, keyid=None, profile=None): ''' Ensure cognito identity pool with passed properties is absent. name The name of the state definition. IdentityPoolName Name of the Cognito Identity Pool. Plea...
Returns true if the passed pcre regex matches
def match(tgt, opts=None): ''' Returns true if the passed pcre regex matches ''' if not opts: return bool(re.match(tgt, __opts__['id'])) else: return bool(re.match(tgt, opts['id']))
Return the running jobs on this minion
def running(opts): ''' Return the running jobs on this minion ''' ret = [] proc_dir = os.path.join(opts['cachedir'], 'proc') if not os.path.isdir(proc_dir): return ret for fn_ in os.listdir(proc_dir): path = os.path.join(proc_dir, fn_) try: data = _read_p...
Write job information to cache
def cache_jobs(opts, jid, ret): ''' Write job information to cache ''' serial = salt.payload.Serial(opts=opts) fn_ = os.path.join( opts['cachedir'], 'minion_jobs', jid, 'return.p') jdir = os.path.dirname(fn_) if not os.path.isdir(jdir): os.makedirs(jd...
Return a dict of JID metadata or None
def _read_proc_file(path, opts): ''' Return a dict of JID metadata, or None ''' serial = salt.payload.Serial(opts) current_thread = threading.currentThread().name pid = os.getpid() with salt.utils.files.fopen(path, 'rb') as fp_: buf = fp_.read() fp_.close() if buf: ...
In some cases where there are an insane number of processes being created on a system a PID can get recycled or assigned to a non - Salt process. On Linux this fn checks to make sure the PID we are checking on is actually a Salt process.
def _check_cmdline(data): ''' In some cases where there are an insane number of processes being created on a system a PID can get recycled or assigned to a non-Salt process. On Linux this fn checks to make sure the PID we are checking on is actually a Salt process. For non-Linux systems we punt...
Return a boolean stating whether or not a file s trailing newline should be removed. To figure this out first check if keep_newline is a boolean and if so return its opposite. Otherwise iterate over keep_newline and check if any of the patterns match the file path. If a match is found return False otherwise return True...
def _check_newline(prefix, file_name, keep_newline): ''' Return a boolean stating whether or not a file's trailing newline should be removed. To figure this out, first check if keep_newline is a boolean and if so, return its opposite. Otherwise, iterate over keep_newline and check if any of the patt...
Construct pillar from file tree.
def _construct_pillar(top_dir, follow_dir_links, keep_newline=False, render_default=None, renderer_blacklist=None, renderer_whitelist=None, template=False): ''' Construct pillar fr...
Compile pillar data from the given root_dir specific to Nodegroup names and Minion IDs.
def ext_pillar(minion_id, pillar, root_dir=None, follow_dir_links=False, debug=False, keep_newline=False, render_default=None, renderer_blacklist=None, renderer_whitelist=None, template...
Compile pillar data for a single root_dir for the specified minion ID
def _ext_pillar(minion_id, root_dir, follow_dir_links, debug, keep_newline, render_default, renderer_blacklist, renderer_whitelist, template): ''' Compile pillar data for a single root...
.. versionchanged:: 2017. 7. 0
def present(name, timespec, tag=None, user=None, job=None, unique_tag=False): ''' .. versionchanged:: 2017.7.0 Add a job to queue. job : string Command to run. timespec : string The 'timespec' follows the format documented in the at(1) manpage. tag : string Make a tag...
.. versionchanged:: 2017. 7. 0
def absent(name, jobid=None, **kwargs): ''' .. versionchanged:: 2017.7.0 Remove a job from queue jobid: string|int Specific jobid to remove tag : string Job's tag runas : string Runs user-specified jobs kwargs Addition kwargs can be provided to filter job...
.. versionadded:: 2017. 7. 0
def watch(name, timespec, tag=None, user=None, job=None, unique_tag=False): ''' .. versionadded:: 2017.7.0 Add an at job if trigger by watch job : string Command to run. timespec : string The 'timespec' follows the format documented in the at(1) manpage. tag : string ...
The at watcher called to invoke the watch command.
def mod_watch(name, **kwargs): ''' The at watcher, called to invoke the watch command. .. note:: This state exists to support special handling of the ``watch`` :ref:`requisite <requisites>`. It should not be called directly. Parameters for this function should be set by the state b...
Return args as a list of strings
def _normalize_args(args): ''' Return args as a list of strings ''' if isinstance(args, six.string_types): return shlex.split(args) if isinstance(args, (tuple, list)): return [six.text_type(arg) for arg in args] else: return [six.text_type(args)]
Return the set of GUIDs found in guid_string
def _find_guids(guid_string): ''' Return the set of GUIDs found in guid_string :param str guid_string: String containing zero or more GUIDs. Each GUID may or may not be enclosed in {} Example data (this string contains two distinct GUIDs): PARENT_SNAPSHOT_ID ...
Execute a prlsrvctl command
def prlsrvctl(sub_cmd, args=None, runas=None): ''' Execute a prlsrvctl command .. versionadded:: 2016.11.0 :param str sub_cmd: prlsrvctl subcommand to execute :param str args: The arguments supplied to ``prlsrvctl <sub_cmd>`` :param str runas: The user that the prlsrv...
List information about the VMs
def list_vms(name=None, info=False, all=False, args=None, runas=None, template=False): ''' List information about the VMs :param str name: Name/ID of VM to list .. versionchanged:: 2016.11.0 No longer implies ``info=True`` :param str info: List extra information ...
Clone a VM
def clone(name, new_name, linked=False, template=False, runas=None): ''' Clone a VM .. versionadded:: 2016.11.0 :param str name: Name/ID of VM to clone :param str new_name: Name of the new VM :param bool linked: Create a linked virtual machine. :param bool templa...
Delete a VM
def delete(name, runas=None): ''' Delete a VM .. versionadded:: 2016.11.0 :param str name: Name/ID of VM to clone :param str runas: The user that the prlctl command will be run as Example: .. code-block:: bash salt '*' parallels.exec macvm 'find /etc/paths.d' ru...
Query whether a VM exists
def exists(name, runas=None): ''' Query whether a VM exists .. versionadded:: 2016.11.0 :param str name: Name/ID of VM :param str runas: The user that the prlctl command will be run as Example: .. code-block:: bash salt '*' parallels.exists macvm runas=macdev ...
Start a VM
def start(name, runas=None): ''' Start a VM :param str name: Name/ID of VM to start :param str runas: The user that the prlctl command will be run as Example: .. code-block:: bash salt '*' parallels.start macvm runas=macdev ''' return prlctl('start', salt.uti...
Stop a VM
def stop(name, kill=False, runas=None): ''' Stop a VM :param str name: Name/ID of VM to stop :param bool kill: Perform a hard shutdown :param str runas: The user that the prlctl command will be run as Example: .. code-block:: bash salt '*' parallels.stop...
Restart a VM by gracefully shutting it down and then restarting it
def restart(name, runas=None): ''' Restart a VM by gracefully shutting it down and then restarting it :param str name: Name/ID of VM to restart :param str runas: The user that the prlctl command will be run as Example: .. code-block:: bash salt '*' parallels.rest...
Reset a VM by performing a hard shutdown and then a restart
def reset(name, runas=None): ''' Reset a VM by performing a hard shutdown and then a restart :param str name: Name/ID of VM to reset :param str runas: The user that the prlctl command will be run as Example: .. code-block:: bash salt '*' parallels.reset macvm runas=m...
Status of a VM
def status(name, runas=None): ''' Status of a VM :param str name: Name/ID of VM whose status will be returned :param str runas: The user that the prlctl command will be run as Example: .. code-block:: bash salt '*' parallels.status macvm runas=macdev ''' retu...
Run a command on a VM
def exec_(name, command, runas=None): ''' Run a command on a VM :param str name: Name/ID of VM whose exec will be returned :param str command: Command to run on the VM :param str runas: The user that the prlctl command will be run as Example: .. code-block:: bash...
Attempt to convert a snapshot ID to a snapshot name. If the snapshot has no name or if the ID is not found or invalid an empty string will be returned
def snapshot_id_to_name(name, snap_id, strict=False, runas=None): ''' Attempt to convert a snapshot ID to a snapshot name. If the snapshot has no name or if the ID is not found or invalid, an empty string will be returned :param str name: Name/ID of VM whose snapshots are inspected :param...
Attempt to convert a snapshot name to a snapshot ID. If the name is not found an empty string is returned. If multiple snapshots share the same name a list will be returned
def snapshot_name_to_id(name, snap_name, strict=False, runas=None): ''' Attempt to convert a snapshot name to a snapshot ID. If the name is not found an empty string is returned. If multiple snapshots share the same name, a list will be returned :param str name: Name/ID of VM whose snapsh...
Validate snapshot name and convert to snapshot ID
def _validate_snap_name(name, snap_name, strict=True, runas=None): ''' Validate snapshot name and convert to snapshot ID :param str name: Name/ID of VM whose snapshot name is being validated :param str snap_name: Name/ID of snapshot :param bool strict: Raise an exception i...
List the snapshots
def list_snapshots(name, snap_name=None, tree=False, names=False, runas=None): ''' List the snapshots :param str name: Name/ID of VM whose snapshots will be listed :param str snap_id: Name/ID of snapshot to display information about. If ``tree=True`` is also specified, display...
Create a snapshot
def snapshot(name, snap_name=None, desc=None, runas=None): ''' Create a snapshot :param str name: Name/ID of VM to take a snapshot of :param str snap_name: Name of snapshot :param str desc: Description of snapshot :param str runas: The user that the prlctl com...
Delete a snapshot
def delete_snapshot(name, snap_name, runas=None, all=False): ''' Delete a snapshot .. note:: Deleting a snapshot from which other snapshots are dervied will not delete the derived snapshots :param str name: Name/ID of VM whose snapshot will be deleted :param str snap_name...
Revert a VM to a snapshot
def revert_snapshot(name, snap_name, runas=None): ''' Revert a VM to a snapshot :param str name: Name/ID of VM to revert to a snapshot :param str snap_name: Name/ID of snapshot to revert to :param str runas: The user that the prlctl command will be run as Example: ...
Executes the given rpc. The returned data can be stored in a file by specifying the destination path with dest as an argument
def rpc(name, dest=None, **kwargs): ''' Executes the given rpc. The returned data can be stored in a file by specifying the destination path with dest as an argument .. code-block:: yaml get-interface-information: junos: - rpc - dest: /home/user/rpc.log ...
Changes the hostname of the device.
def set_hostname(name, **kwargs): ''' Changes the hostname of the device. .. code-block:: yaml device_name: junos: - set_hostname - comment: "Host-name set via saltstack." Parameters: Required * hostname: The name to be set. (def...
Commits the changes loaded into the candidate configuration.
def commit(name, **kwargs): ''' Commits the changes loaded into the candidate configuration. .. code-block:: yaml commit the changes: junos: - commit - confirm: 10 Parameters: Optional * kwargs: Keyworded arguments which can be ...
Rollbacks the committed changes.
def rollback(name, **kwargs): ''' Rollbacks the committed changes. .. code-block:: yaml rollback the changes: junos: - rollback - id: 5 Parameters: Optional * id: The rollback id value [0-49]. (default = 0) * kw...
Gets the difference between the candidate and the current configuration.
def diff(name, **kwargs): ''' Gets the difference between the candidate and the current configuration. .. code-block:: yaml get the diff: junos: - diff - id: 10 Parameters: Optional * id: The rollback id value [0-49]. (...
Executes the CLI commands and reuturns the text output.
def cli(name, format='text', **kwargs): ''' Executes the CLI commands and reuturns the text output. .. code-block:: yaml show version: junos: - cli - format: xml Parameters: Required * command: The command that need to ...
Shuts down the device.
def shutdown(name, **kwargs): ''' Shuts down the device. .. code-block:: yaml shut the device: junos: - shutdown - in_min: 10 Parameters: Optional * kwargs: * reboot: Whether to reboot instead of shutdow...
Loads and commits the configuration provided.
def install_config(name, **kwargs): ''' Loads and commits the configuration provided. .. code-block:: yaml Install the mentioned config: junos: - install_config - path: salt//configs/interface.set - timeout: 100 - di...
Installs the given image on the device. After the installation is complete the device is rebooted if reboot = True is given as a keyworded argument.
def install_os(name, **kwargs): ''' Installs the given image on the device. After the installation is complete the device is rebooted, if reboot=True is given as a keyworded argument. .. code-block:: yaml salt://images/junos_image.tgz: junos: - install_os ...
Copies the file from the local device to the junos device.
def file_copy(name, dest=None, **kwargs): ''' Copies the file from the local device to the junos device. .. code-block:: yaml /home/m2/info.txt: junos: - file_copy - dest: info_copy.txt Parameters: Required * src: The s...
Loads the configuration provided onto the junos device.
def load(name, **kwargs): ''' Loads the configuration provided onto the junos device. .. code-block:: yaml Install the mentioned config: junos: - load - path: salt//configs/interface.set .. code-block:: yaml Install the mentioned ...
Retrieve data from a Junos device using Tables/ Views
def get_table(name, table, table_file, **kwargs): ''' Retrieve data from a Junos device using Tables/Views name (required) task definition table (required) Name of PyEZ Table file YAML file that has the table specified in table parameter path: Path of location...
Create a file system on the specified device
def mkfs(device, fs_type, **kwargs): ''' Create a file system on the specified device CLI Example: .. code-block:: bash salt '*' extfs.mkfs /dev/sda1 fs_type=ext4 opts='acl,noexec' Valid options are: * **block_size**: 1024, 2048 or 4096 * **check**: check for bad blocks * **...
Set attributes for the specified device ( using tune2fs )
def tune(device, **kwargs): ''' Set attributes for the specified device (using tune2fs) CLI Example: .. code-block:: bash salt '*' extfs.tune /dev/sda1 force=True label=wildstallyns opts='acl,noexec' Valid options are: * **max**: max mount count * **count**: mount count * **...
Return all contents of dumpe2fs for a specified device
def dump(device, args=None): ''' Return all contents of dumpe2fs for a specified device CLI Example: .. code-block:: bash salt '*' extfs.dump /dev/sda1 ''' cmd = 'dumpe2fs {0}'.format(device) if args: cmd = cmd + ' -' + args ret = {'attributes': {}, 'blocks': {}} o...
ZeroMQ python bindings > = 2. 1. 9 are required
def zmq_version(): ''' ZeroMQ python bindings >= 2.1.9 are required ''' try: import zmq except Exception: # Return True for local mode return True ver = zmq.__version__ # The last matched group can be None if the version # is something like 3.1 and that will work ...
Lookup a hostname and determine its address family. The first address returned will be AF_INET6 if the system is IPv6 - enabled and AF_INET otherwise.
def lookup_family(hostname): ''' Lookup a hostname and determine its address family. The first address returned will be AF_INET6 if the system is IPv6-enabled, and AF_INET otherwise. ''' # If lookups fail, fall back to AF_INET sockets (and v4 addresses). fallback = socket.AF_INET try: ...
Attempt to bind to the sockets to verify that they are available
def verify_socket(interface, pub_port, ret_port): ''' Attempt to bind to the sockets to verify that they are available ''' addr_family = lookup_family(interface) for port in pub_port, ret_port: sock = socket.socket(addr_family, socket.SOCK_STREAM) try: sock.setsockopt(so...
Verify that the named files exist and are owned by the named user
def verify_files(files, user): ''' Verify that the named files exist and are owned by the named user ''' if salt.utils.platform.is_windows(): return True import pwd # after confirming not running Windows try: pwnam = pwd.getpwnam(user) uid = pwnam[2] except KeyError:...
Verify that the named directories are in place and that the environment can shake the salt
def verify_env( dirs, user, permissive=False, pki_dir='', skip_extra=False, root_dir=ROOT_DIR): ''' Verify that the named directories are in place and that the environment can shake the salt ''' if salt.utils.platform.is_windows(): return win_v...
Check user and assign process uid/ gid.
def check_user(user): ''' Check user and assign process uid/gid. ''' if salt.utils.platform.is_windows(): return True if user == salt.utils.user.get_user(): return True import pwd # after confirming not running Windows try: pwuser = pwd.getpwnam(user) try: ...
Returns a full list of directories leading up to and including a path.
def list_path_traversal(path): ''' Returns a full list of directories leading up to, and including, a path. So list_path_traversal('/path/to/salt') would return: ['/', '/path', '/path/to', '/path/to/salt'] in that order. This routine has been tested on Windows systems as well. list_pat...
Walk from the root up to a directory and verify that the current user has access to read each directory. This is used for making sure a user can read all parent directories of the minion s key before trying to go and generate a new key and raising an IOError
def check_path_traversal(path, user='root', skip_perm_errors=False): ''' Walk from the root up to a directory and verify that the current user has access to read each directory. This is used for making sure a user can read all parent directories of the minion's key before trying to go and generate...
Check the number of max allowed open files and adjust if needed
def check_max_open_files(opts): ''' Check the number of max allowed open files and adjust if needed ''' mof_c = opts.get('max_open_files', 100000) if sys.platform.startswith('win'): # Check the Windows API for more detail on this # http://msdn.microsoft.com/en-us/library/xt874334(v=v...
Accepts the root the path needs to be under and verifies that the path is under said root. Pass in subdir = True if the path can result in a subdirectory of the root instead of having to reside directly in the root
def clean_path(root, path, subdir=False): ''' Accepts the root the path needs to be under and verifies that the path is under said root. Pass in subdir=True if the path can result in a subdirectory of the root instead of having to reside directly in the root ''' if not os.path.isabs(root): ...
Returns if the passed id is valid
def valid_id(opts, id_): ''' Returns if the passed id is valid ''' try: if any(x in id_ for x in ('/', '\\', str('\0'))): return False return bool(clean_path(opts['pki_dir'], id_)) except (AttributeError, KeyError, TypeError, UnicodeDecodeError): return False
Check a string to see if it has any potentially unsafe routines which could be executed via python this routine is used to improve the safety of modules suct as virtualenv
def safe_py_code(code): ''' Check a string to see if it has any potentially unsafe routines which could be executed via python, this routine is used to improve the safety of modules suct as virtualenv ''' bads = ( 'import', ';', 'subprocess', 'eval...
If an insecre logging configuration is found show a warning
def verify_log(opts): ''' If an insecre logging configuration is found, show a warning ''' level = LOG_LEVELS.get(str(opts.get('log_level')).lower(), logging.NOTSET) if level < logging.INFO: log.warning('Insecure logging configuration detected! Sensitive data may be logged.')
Verify that the named directories are in place and that the environment can shake the salt
def win_verify_env( path, dirs, permissive=False, pki_dir='', skip_extra=False): ''' Verify that the named directories are in place and that the environment can shake the salt ''' import salt.utils.win_functions import salt.utils.win_dacl import salt.u...
List all available package upgrades on this system
def list_upgrades(refresh=False, root=None, **kwargs): # pylint: disable=W0613 ''' List all available package upgrades on this system CLI Example: .. code-block:: bash salt '*' pkg.list_upgrades ''' upgrades = {} cmd = ['pacman', '-S', '-p', '-u', '--print-format', '%n %v'] ...
List the packages currently installed as a dict::
def list_pkgs(versions_as_list=False, **kwargs): ''' List the packages currently installed as 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...
.. versionadded:: 2016. 11. 0
def group_list(): ''' .. versionadded:: 2016.11.0 Lists all groups known by pacman on this system CLI Example: .. code-block:: bash salt '*' pkg.group_list ''' ret = {'installed': [], 'partially_installed': [], 'available': []} # find out what's available ...
.. versionadded:: 2016. 11. 0
def group_info(name): ''' .. versionadded:: 2016.11.0 Lists all packages in the specified group CLI Example: .. code-block:: bash salt '*' pkg.group_info 'xorg' ''' pkgtypes = ('mandatory', 'optional', 'default', 'conditional') ret = {} for pkgtype in pkgtypes: r...
.. versionadded:: 2016. 11. 0
def group_diff(name): ''' .. versionadded:: 2016.11.0 Lists which of a group's packages are installed and which are not installed Compatible with yumpkg.group_diff for easy support of state.pkg.group_installed CLI Example: .. code-block:: bash salt '*' pkg.group_diff 'xorg' ...
Just run a pacman - Sy return a dict::
def refresh_db(root=None, **kwargs): ''' Just run a ``pacman -Sy``, return a dict:: {'<database name>': Bool} CLI Example: .. code-block:: bash salt '*' pkg.refresh_db ''' # Remove rtag file to keep multiple refreshes from happening in pkg states salt.utils.pkg.clear_rtag...
.. 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 pacman commands spawned by Salt when the salt - min...
def install(name=None, refresh=False, sysupgrade=None, pkgs=None, sources=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 mod...
.. 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 pacman commands spawned by Salt when the salt - min...
def upgrade(refresh=False, root=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. This is done to keep s...
remove and purge do identical things but with different pacman commands this function performs the common logic.
def _uninstall(action='remove', name=None, pkgs=None, **kwargs): ''' remove and purge do identical things but with different pacman commands, this function performs the common logic. ''' try: pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0] except MinionError as exc: ...
List the files that belong to a package. Not specifying any packages will return a list of _every_ file on the system s package database ( not generally recommended ).
def file_list(*packages, **kwargs): ''' List the files that belong to a package. Not specifying any packages will return a list of _every_ file on the system's package database (not generally recommended). CLI Examples: .. code-block:: bash salt '*' pkg.file_list httpd salt '*...
Returns all available packages. Optionally package names ( and name globs ) can be passed and the results will be filtered to packages matching those names.
def list_repo_pkgs(*args, **kwargs): ''' Returns all available packages. Optionally, package names (and name globs) can be passed and the results will be filtered to packages matching those names. This function can be helpful in discovering the version or repo to specify in a :mod:`pkg.installe...
Run the api
def run(self): ''' Run the api ''' ui = salt.spm.SPMCmdlineInterface() self.parse_args() self.setup_logfile_logger() v_dirs = [ self.config['spm_cache_dir'], ] verify_env(v_dirs, self.config['user'], ...
This function normalizes the config block into a set of queries we can use. The return is a list of consistently laid out dicts.
def extract_queries(self, args, kwargs): ''' This function normalizes the config block into a set of queries we can use. The return is a list of consistently laid out dicts. ''' # Please note the function signature is NOT an error. Neither args, nor # kwargs should have...
Set self. focus for kwarg queries
def enter_root(self, root): ''' Set self.focus for kwarg queries ''' # There is no collision protection on root name isolation if root: self.result[root] = self.focus = {} else: self.focus = self.result
The primary purpose of this function is to store the sql field list and the depth to which we process.
def process_fields(self, field_names, depth): ''' The primary purpose of this function is to store the sql field list and the depth to which we process. ''' # List of field names in correct order. self.field_names = field_names # number of fields. self.num...
This function takes a list of database results and iterates over merging them into a dict form.
def process_results(self, rows): ''' This function takes a list of database results and iterates over, merging them into a dict form. ''' listify = OrderedDict() listify_dicts = OrderedDict() for ret in rows: # crd is the Current Return Data level, to ...
Execute queries merge and return as a dict.
def fetch(self, minion_id, pillar, # pylint: disable=W0613 *args, **kwargs): ''' Execute queries, merge and return as a dict. ''' db_name = self._db_name() log.info('Querying %s for information for %s', db_name, minion_id) ...
Internal returns bridges and enslaved interfaces ( GNU/ Linux - brctl )
def _linux_brshow(br=None): ''' Internal, returns bridges and enslaved interfaces (GNU/Linux - brctl) ''' brctl = _tool_path('brctl') if br: cmd = '{0} show {1}'.format(brctl, br) else: cmd = '{0} show'.format(brctl) brs = {} for line in __salt__['cmd.run'](cmd, python...
Internal creates the bridge
def _linux_bradd(br): ''' Internal, creates the bridge ''' brctl = _tool_path('brctl') return __salt__['cmd.run']('{0} addbr {1}'.format(brctl, br), python_shell=False)
Internal deletes the bridge
def _linux_brdel(br): ''' Internal, deletes the bridge ''' brctl = _tool_path('brctl') return __salt__['cmd.run']('{0} delbr {1}'.format(brctl, br), python_shell=False)
Internal removes an interface from a bridge
def _linux_delif(br, iface): ''' Internal, removes an interface from a bridge ''' brctl = _tool_path('brctl') return __salt__['cmd.run']('{0} delif {1} {2}'.format(brctl, br, iface), python_shell=False)
Internal sets STP state
def _linux_stp(br, state): ''' Internal, sets STP state ''' brctl = _tool_path('brctl') return __salt__['cmd.run']('{0} stp {1} {2}'.format(brctl, br, state), python_shell=False)
Internal returns bridges and member interfaces ( BSD - like: ifconfig )
def _bsd_brshow(br=None): ''' Internal, returns bridges and member interfaces (BSD-like: ifconfig) ''' if __grains__['kernel'] == 'NetBSD': return _netbsd_brshow(br) ifconfig = _tool_path('ifconfig') ifaces = {} if br: ifaces[br] = br else: cmd = '{0} -g bridge...
Internal returns bridges and enslaved interfaces ( NetBSD - brconfig )
def _netbsd_brshow(br=None): ''' Internal, returns bridges and enslaved interfaces (NetBSD - brconfig) ''' brconfig = _tool_path('brconfig') if br: cmd = '{0} {1}'.format(brconfig, br) else: cmd = '{0} -a'.format(brconfig) brs = {} start_int = False for line in __s...
Internal creates the bridge
def _bsd_bradd(br): ''' Internal, creates the bridge ''' kernel = __grains__['kernel'] ifconfig = _tool_path('ifconfig') if not br: return False if __salt__['cmd.retcode']('{0} {1} create up'.format(ifconfig, br), python_shell=False) != 0: ret...
Internal deletes the bridge
def _bsd_brdel(br): ''' Internal, deletes the bridge ''' ifconfig = _tool_path('ifconfig') if not br: return False return __salt__['cmd.run']('{0} {1} destroy'.format(ifconfig, br), python_shell=False)
Internal adds an interface to a bridge
def _bsd_addif(br, iface): ''' Internal, adds an interface to a bridge ''' kernel = __grains__['kernel'] if kernel == 'NetBSD': cmd = _tool_path('brconfig') brcmd = 'add' else: cmd = _tool_path('ifconfig') brcmd = 'addem' if not br or not iface: retur...
Internal sets STP state. On BSD - like it is required to specify the STP physical interface
def _bsd_stp(br, state, iface): ''' Internal, sets STP state. On BSD-like, it is required to specify the STP physical interface ''' kernel = __grains__['kernel'] if kernel == 'NetBSD': cmd = _tool_path('brconfig') else: cmd = _tool_path('ifconfig') if not br or not iface...
Internal dispatches functions by operating system
def _os_dispatch(func, *args, **kwargs): ''' Internal, dispatches functions by operating system ''' if __grains__['kernel'] in SUPPORTED_BSD_LIKE: kernel = 'bsd' else: kernel = __grains__['kernel'].lower() _os_func = getattr(sys.modules[__name__], '_{0}_{1}'.format(kernel, func)...
Returns the machine s bridges list
def list_(): ''' Returns the machine's bridges list CLI Example: .. code-block:: bash salt '*' bridge.list ''' brs = _os_dispatch('brshow') if not brs: return None brlist = [] for br in brs: brlist.append(br) return brlist
Returns the bridge to which the interfaces are bond to
def find_interfaces(*args): ''' Returns the bridge to which the interfaces are bond to CLI Example: .. code-block:: bash salt '*' bridge.find_interfaces eth0 [eth1...] ''' brs = _os_dispatch('brshow') if not brs: return None iflist = {} for iface in args: ...
Sets Spanning Tree Protocol state for a bridge
def stp(br=None, state='disable', iface=None): ''' Sets Spanning Tree Protocol state for a bridge CLI Example: .. code-block:: bash salt '*' bridge.stp br0 enable salt '*' bridge.stp br0 disable For BSD-like operating systems, it is required to add the interface on which to e...