INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Apply the loaded cloud providers configuration.
def apply_cloud_providers_config(overrides, defaults=None): ''' Apply the loaded cloud providers configuration. ''' if defaults is None: defaults = PROVIDER_CONFIG_DEFAULTS config = defaults.copy() if overrides: config.update(overrides) # Is the user still using the old for...
Search and return a setting in a known order:
def get_cloud_config_value(name, vm_, opts, default=None, search_global=True): ''' Search and return a setting in a known order: 1. In the virtual machine's configuration 2. In the virtual machine's profile configuration 3. In the virtual machine's provider configuration 4. In t...
Check and return the first matching and fully configured cloud provider configuration.
def is_provider_configured(opts, provider, required_keys=(), log_message=True, aliases=()): ''' Check and return the first matching and fully configured cloud provider configuration. ''' if ':' in provider: alias, driver = provider.split(':') if alias not in opts['providers']: ...
Check if the requested profile contains the minimum required parameters for a profile.
def is_profile_configured(opts, provider, profile_name, vm_=None): ''' Check if the requested profile contains the minimum required parameters for a profile. Required parameters include image and provider for all drivers, while some drivers also require size keys. .. versionadded:: 2015.8.0 ...
Check if the driver s dependencies are available.
def check_driver_dependencies(driver, dependencies): ''' Check if the driver's dependencies are available. .. versionadded:: 2015.8.0 driver The name of the driver. dependencies The dictionary of dependencies to check. ''' ret = True for key, value in six.iteritems(dep...
Helper function writes minion id to a cache file.
def _cache_id(minion_id, cache_file): ''' Helper function, writes minion id to a cache file. ''' path = os.path.dirname(cache_file) try: if not os.path.isdir(path): os.makedirs(path) except OSError as exc: # Handle race condition where dir is created after os.path.isd...
Evaluate the function that determines the ID if the id_function option is set and return the result
def call_id_function(opts): ''' Evaluate the function that determines the ID if the 'id_function' option is set and return the result ''' if opts.get('id'): return opts['id'] # Import 'salt.loader' here to avoid a circular dependency import salt.loader as loader if isinstance(o...
Depending on the values of minion_id_remove_domain remove all domains or a single domain from a FQDN effectivly generating a hostname.
def remove_domain_from_fqdn(opts, newid): ''' Depending on the values of `minion_id_remove_domain`, remove all domains or a single domain from a FQDN, effectivly generating a hostname. ''' opt_domain = opts.get('minion_id_remove_domain') if opt_domain is True: if '.' in newid: ...
Guess the id of the minion.
def get_id(opts, cache_minion_id=False): ''' Guess the id of the minion. If CONFIG_DIR/minion_id exists, use the cached minion ID from that file. If no minion id is configured, use multiple sources to find a FQDN. If no FQDN is found you may get an ip address. Returns two values: the detected ...
Resolves string names to integer constant in ssl configuration.
def _update_ssl_config(opts): ''' Resolves string names to integer constant in ssl configuration. ''' if opts['ssl'] in (None, False): opts['ssl'] = None return if opts['ssl'] is True: opts['ssl'] = {} return import ssl for key, prefix in (('cert_reqs', 'CERT_...
Adjusts the log_file based on the log_dir override
def _adjust_log_file_override(overrides, default_log_file): ''' Adjusts the log_file based on the log_dir override ''' if overrides.get('log_dir'): # Adjust log_file if a log_dir override is introduced if overrides.get('log_file'): if not os.path.isabs(overrides['log_file']):...
Returns minion configurations dict.
def apply_minion_config(overrides=None, defaults=None, cache_minion_id=False, minion_id=None): ''' Returns minion configurations dict. ''' if defaults is None: defaults = DEFAULT_MINION_OPTS.copy() if overrides is None: ...
Update discovery config for all instances.
def _update_discovery_config(opts): ''' Update discovery config for all instances. :param opts: :return: ''' if opts.get('discovery') not in (None, False): if opts['discovery'] is True: opts['discovery'] = {} discovery_config = {'attempts': 3, 'pause': 5, 'port': 452...
Reads in the master configuration file and sets up default options
def master_config(path, env_var='SALT_MASTER_CONFIG', defaults=None, exit_on_config_errors=False): ''' Reads in the master configuration file and sets up default options This is useful for running the actual master daemon. For running Master-side client interfaces that need the master opts see :py:...
Returns master configurations dict.
def apply_master_config(overrides=None, defaults=None): ''' Returns master configurations dict. ''' if defaults is None: defaults = DEFAULT_MASTER_OPTS.copy() if overrides is None: overrides = {} opts = defaults.copy() opts['__role'] = 'master' _adjust_log_file_override(...
Load Master configuration data
def client_config(path, env_var='SALT_CLIENT_CONFIG', defaults=None): ''' Load Master configuration data Usage: .. code-block:: python import salt.config master_opts = salt.config.client_config('/etc/salt/master') Returns a dictionary of the Salt Master configuration file with ne...
Read in the Salt Master config file and add additional configs that need to be stubbed out for salt - api
def api_config(path): ''' Read in the Salt Master config file and add additional configs that need to be stubbed out for salt-api ''' # Let's grab a copy of salt-api's required defaults opts = DEFAULT_API_OPTS.copy() # Let's override them with salt's master opts opts.update(client_confi...
Read in the salt master config file and add additional configs that need to be stubbed out for spm
def spm_config(path): ''' Read in the salt master config file and add additional configs that need to be stubbed out for spm .. versionadded:: 2015.8.0 ''' # Let's grab a copy of salt's master default opts defaults = DEFAULT_MASTER_OPTS.copy() # Let's override them with spm's required d...
Returns the spm configurations dict.
def apply_spm_config(overrides, defaults): ''' Returns the spm configurations dict. .. versionadded:: 2015.8.1 ''' opts = defaults.copy() _adjust_log_file_override(overrides, defaults['log_file']) if overrides: opts.update(overrides) # Prepend root_dir to other paths prepen...
Render config template substituting grains where found.
def _render_template(config_file): ''' Render config template, substituting grains where found. ''' dirname, filename = os.path.split(config_file) env = jinja2.Environment(loader=jinja2.FileSystemLoader(dirname)) template = env.get_template(filename) return template.render(__grains__)
Return a value for name from the config file options. If the name is not in the config the default value is returned. This method converts unicode values to str type under python 2.
def _config(name, conf, default=None): ''' Return a value for 'name' from the config file options. If the 'name' is not in the config, the 'default' value is returned. This method converts unicode values to str type under python 2. ''' try: value = conf[name] except KeyError: ...
Aggregates LDAP search result based on rules returns a dictionary.
def _result_to_dict(data, result, conf, source): ''' Aggregates LDAP search result based on rules, returns a dictionary. Rules: Attributes tagged in the pillar config as 'attrs' or 'lists' are scanned for a 'key=value' format (non matching entries are ignored. Entries matching the 'attrs' tag ...
Builds connection and search arguments performs the LDAP search and formats the results as a dictionary appropriate for pillar use.
def _do_search(conf): ''' Builds connection and search arguments, performs the LDAP search and formats the results as a dictionary appropriate for pillar use. ''' # Build LDAP connection args connargs = {} for name in ['server', 'port', 'tls', 'binddn', 'bindpw', 'anonymous']: connar...
Execute LDAP searches and return the aggregated data
def ext_pillar(minion_id, # pylint: disable=W0613 pillar, # pylint: disable=W0613 config_file): ''' Execute LDAP searches and return the aggregated data ''' config_template = None try: config_template = _render_template(config_file) except jinja2.exception...
Import the certificate file into the given certificate store.
def import_cert(name, cert_format=_DEFAULT_FORMAT, context=_DEFAULT_CONTEXT, store=_DEFAULT_STORE, exportable=True, password='', saltenv='base'): ''' Import the certificate file into the given certificate store. :param str name: The path of the certificate file to import. :param str cer...
Remove the certificate from the given certificate store.
def remove_cert(name, thumbprint, context=_DEFAULT_CONTEXT, store=_DEFAULT_STORE): ''' Remove the certificate from the given certificate store. :param str thumbprint: The thumbprint value of the target certificate. :param str context: The name of the certificate store location context. :param str s...
Set a key/ value pair in the etcd service
def set_(key, value, service=None, profile=None): # pylint: disable=W0613 ''' Set a key/value pair in the etcd service ''' client = _get_conn(profile) client.set(key, value) return get(key, service, profile)
Get a value from the etcd service
def get(key, service=None, profile=None): # pylint: disable=W0613 ''' Get a value from the etcd service ''' client = _get_conn(profile) result = client.get(key) return result.value
Get a value from the etcd service
def delete(key, service=None, profile=None): # pylint: disable=W0613 ''' Get a value from the etcd service ''' client = _get_conn(profile) try: client.delete(key) return True except Exception: return False
.. versionadded:: 2014. 7. 0
def chain_present(name, table='filter', table_type=None, hook=None, priority=None, family='ipv4'): ''' .. versionadded:: 2014.7.0 Verify the chain is exist. name A user-defined chain name. table The table to own the chain. family Networking family, either ipv4 or ipv6...
.. versionadded:: 2014. 7. 0
def chain_absent(name, table='filter', family='ipv4'): ''' .. versionadded:: 2014.7.0 Verify the chain is absent. family Networking family, either ipv4 or ipv6 ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} chain_check = __...
.. versionadded:: 0. 17. 0
def append(name, family='ipv4', **kwargs): ''' .. versionadded:: 0.17.0 Append a rule to a chain name A user-defined name to call this rule by in another part of a state or formula. This should not be an actual rule. family Network family, ipv4 or ipv6. All other argu...
.. versionadded:: 2014. 7. 0
def flush(name, family='ipv4', **kwargs): ''' .. versionadded:: 2014.7.0 Flush current nftables state family Networking family, either ipv4 or ipv6 ''' ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''} for ignore in _STATE_INTERNA...
Execute Riak commands
def __execute_cmd(name, cmd): ''' Execute Riak commands ''' return __salt__['cmd.run_all']( '{0} {1}'.format(salt.utils.path.which(name), cmd) )
Start Riak
def start(): ''' Start Riak CLI Example: .. code-block:: bash salt '*' riak.start ''' ret = {'comment': '', 'success': False} cmd = __execute_cmd('riak', 'start') if cmd['retcode'] != 0: ret['comment'] = cmd['stderr'] else: ret['comment'] = cmd['stdout'] ...
Stop Riak
def stop(): ''' Stop Riak .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.stop ''' ret = {'comment': '', 'success': False} cmd = __execute_cmd('riak', 'stop') if cmd['retcode'] != 0: ret['comment'] = cmd['stderr'] else: r...
Join a Riak cluster
def cluster_join(username, hostname): ''' Join a Riak cluster .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.cluster_join <user> <host> username - The riak username to join the cluster hostname - The riak hostname you are connecting to ''' r...
Commit Cluster Changes
def cluster_commit(): ''' Commit Cluster Changes .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.cluster_commit ''' ret = {'comment': '', 'success': False} cmd = __execute_cmd('riak-admin', 'cluster commit') if cmd['retcode'] != 0: r...
Get cluster member status
def member_status(): ''' Get cluster member status .. versionchanged:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.member_status ''' ret = {'membership': {}, 'summary': {'Valid': 0, 'Leaving': 0, 'Exiting': 0, ...
Current node status
def status(): ''' Current node status .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' riak.status ''' ret = {} cmd = __execute_cmd('riak-admin', 'status') for i in cmd['stdout'].splitlines(): if ':' in i: (name, val) = i.split('...
Enforce the given flags on the given package or DEPEND atom.
def flags(name, use=None, accept_keywords=None, env=None, license=None, properties=None, unmask=False, mask=False): ''' Enforce the given flags on the given package or ``DEPEND`` atom. .. warning:: In most cases, the affected pa...
Add a user to htpasswd file using the htpasswd command. If the htpasswd file does not exist it will be created.
def useradd(pwfile, user, password, opts='', runas=None): ''' Add a user to htpasswd file using the htpasswd command. If the htpasswd file does not exist, it will be created. pwfile Path to htpasswd file user User name password User password opts Valid opt...
Delete a user from the specified htpasswd file.
def userdel(pwfile, user, runas=None, all_results=False): ''' Delete a user from the specified htpasswd file. pwfile Path to htpasswd file user User name runas The system user to run htpasswd command with all_results Return stdout, stderr, and retcode, not jus...
Return True if the htpasswd file exists the user has an entry and their password matches.
def verify(pwfile, user, password, opts='', runas=None): ''' Return True if the htpasswd file exists, the user has an entry, and their password matches. pwfile Fully qualified path to htpasswd file user User name password User password opts Valid options t...
Is the passed user a member of the Administrators group
def is_admin(name): ''' Is the passed user a member of the Administrators group Args: name (str): The name to check Returns: bool: True if user is a member of the Administrators group, False otherwise ''' groups = get_user_groups(name, True) for group in groups: ...
Get the groups to which a user belongs
def get_user_groups(name, sid=False): ''' Get the groups to which a user belongs Args: name (str): The user name to query sid (bool): True will return a list of SIDs, False will return a list of group names Returns: list: A list of group names or sids ''' if nam...
This is a tool for getting a sid from a name. The name can be any object. Usually a user or a group
def get_sid_from_name(name): ''' This is a tool for getting a sid from a name. The name can be any object. Usually a user or a group Args: name (str): The name of the user or group for which to get the sid Returns: str: The corresponding SID ''' # If None is passed, use the...
Gets the user executing the process
def get_current_user(with_domain=True): ''' Gets the user executing the process Args: with_domain (bool): ``True`` will prepend the user name with the machine name or domain separated by a backslash Returns: str: The user name ''' try: user_name...
r Gets the SAM name for a user. It basically prefixes a username without a backslash with the computer name. If the user does not exist a SAM compatible name will be returned using the local hostname as the domain.
def get_sam_name(username): r''' Gets the SAM name for a user. It basically prefixes a username without a backslash with the computer name. If the user does not exist, a SAM compatible name will be returned using the local hostname as the domain. i.e. salt.utils.get_same_name('Administrator') would...
Escape the argument for the cmd. exe shell. See http:// blogs. msdn. com/ b/ twistylittlepassagesallalike/ archive/ 2011/ 04/ 23/ everyone - quotes - arguments - the - wrong - way. aspx
def escape_argument(arg, escape=True): ''' Escape the argument for the cmd.exe shell. See http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx First we escape the quote chars to produce a argument suitable for CommandLineToArgvW. We do...
Escape an argument string to be suitable to be passed to cmd. exe on Windows
def escape_for_cmd_exe(arg): ''' Escape an argument string to be suitable to be passed to cmd.exe on Windows This method takes an argument that is expected to already be properly escaped for the receiving program to be properly parsed. This argument will be further escaped to pass the interpola...
Send a WM_SETTINGCHANGE Broadcast to all Windows
def broadcast_setting_change(message='Environment'): ''' Send a WM_SETTINGCHANGE Broadcast to all Windows Args: message (str): A string value representing the portion of the system that has been updated and needs to be refreshed. Default is ``Environment``. These ...
Converts a GUID to a compressed guid ( SQUID )
def guid_to_squid(guid): ''' Converts a GUID to a compressed guid (SQUID) Each Guid has 5 parts separated by '-'. For the first three each one will be totally reversed, and for the remaining two each one will be reversed by every other character. Then the final compressed Guid will be constructed...
Converts a compressed GUID ( SQUID ) back into a GUID
def squid_to_guid(squid): ''' Converts a compressed GUID (SQUID) back into a GUID Args: squid (str): A valid compressed GUID Returns: str: A valid GUID ''' squid_pattern = re.compile(r'^(\w{8})(\w{4})(\w{4})(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)(\w\w)$') squid_match = ...
Gathers the data from the specified minions mine pass in the target function to look up and the target type
def get(tgt, fun, tgt_type='glob'): ''' Gathers the data from the specified minions' mine, pass in the target, function to look up and the target type CLI Example: .. code-block:: bash salt-run mine.get '*' network.interfaces ''' ret = salt.utils.minions.mine_get(tgt, fun, tgt_typ...
.. versionadded:: 2017. 7. 0
def update(tgt, tgt_type='glob', clear=False, mine_functions=None): ''' .. versionadded:: 2017.7.0 Update the mine data on a certain group of minions. tgt Which minions to target for the execution. tgt_type: ``glob`` The type of ``tgt``. clear...
Send exec and config commands to the NX - OS device over NX - API.
def nxapi_request(commands, method='cli_show', **kwargs): ''' Send exec and config commands to the NX-OS device over NX-API. commands The exec or config commands to be sent. method: ``cli_show_ascii``: Return raw test or unstructured output. ...
Helper method to return parsed system_info from the show version command.
def system_info(data): ''' Helper method to return parsed system_info from the 'show version' command. ''' if not data: return {} info = { 'software': _parse_software(data), 'hardware': _parse_hardware(data), 'plugins': _parse_plugins(data), } return {'nxo...
Determine if connection is local or remote
def _use_remote_connection(self, kwargs): ''' Determine if connection is local or remote ''' kwargs['host'] = kwargs.get('host') kwargs['username'] = kwargs.get('username') kwargs['password'] = kwargs.get('password') if kwargs['host'] is None or \ kwarg...
Set connection arguments for remote or local connection.
def _prepare_conn_args(self, kwargs): ''' Set connection arguments for remote or local connection. ''' kwargs['connect_over_uds'] = True kwargs['timeout'] = kwargs.get('timeout', 60) kwargs['cookie'] = kwargs.get('cookie', 'admin') if self._use_remote_connection(k...
Build NX - API JSON request.
def _build_request(self, type, commands): ''' Build NX-API JSON request. ''' request = {} headers = { 'content-type': 'application/json', } if self.nxargs['connect_over_uds']: user = self.nxargs['cookie'] headers['cookie'] = 'nx...
Send NX - API JSON request to the NX - OS device.
def request(self, type, command_list): ''' Send NX-API JSON request to the NX-OS device. ''' req = self._build_request(type, command_list) if self.nxargs['connect_over_uds']: self.connection.request('POST', req['url'], req['payload'], req['headers']) respo...
Parse NX - API JSON response from the NX - OS device.
def parse_response(self, response, command_list): ''' Parse NX-API JSON response from the NX-OS device. ''' # Check for 500 level NX-API Server Errors if isinstance(response, collections.Iterable) and 'status' in response: if int(response['status']) >= 500: ...
Get a list of the PowerShell modules which are potentially available to be imported. The intent is to mimic the functionality of Get - Module - ListAvailable | Select - Object - Expand Name without the delay of loading PowerShell to do so.
def get_modules(): ''' Get a list of the PowerShell modules which are potentially available to be imported. The intent is to mimic the functionality of ``Get-Module -ListAvailable | Select-Object -Expand Name``, without the delay of loading PowerShell to do so. Returns: list: A list of ...
Generate an icinga2 client certificate and key.
def generate_cert(domain): ''' Generate an icinga2 client certificate and key. Returns:: icinga2 pki new-cert --cn domain.tld --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt CLI Example: .. code-block:: bash salt '*' icinga2.generate_cert domain.tld ...
Save the certificate for master icinga2 node.
def save_cert(domain, master): ''' Save the certificate for master icinga2 node. Returns:: icinga2 pki save-cert --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt --trustedcert /etc/icinga2/pki/trusted-master.crt --host master.domain.tld CLI Example: .. code-blo...
Request CA cert from master icinga2 node.
def request_cert(domain, master, ticket, port): ''' Request CA cert from master icinga2 node. Returns:: icinga2 pki request --host master.domain.tld --port 5665 --ticket TICKET_ID --key /etc/icinga2/pki/domain.tld.key --cert /etc/icinga2/pki/domain.tld.crt --trustedcert \ /etc/icing...
Setup the icinga2 node.
def node_setup(domain, master, ticket): ''' Setup the icinga2 node. Returns:: icinga2 node setup --ticket TICKET_ID --endpoint master.domain.tld --zone domain.tld --master_host master.domain.tld --trustedcert \ /etc/icinga2/pki/trusted-master.crt CLI Example: .. code-block...
Handles salt_host resources. See https:// github. com/ dmacvicar/ terraform - provider - salt
def _handle_salt_host_resource(resource): ''' Handles salt_host resources. See https://github.com/dmacvicar/terraform-provider-salt Returns roster attributes for the resource or None ''' ret = {} attrs = resource.get('primary', {}).get('attributes', {}) ret[MINION_ID] = attrs.get(MINION...
Setups the salt - ssh minion to be accessed with salt - ssh default key
def _add_ssh_key(ret): ''' Setups the salt-ssh minion to be accessed with salt-ssh default key ''' priv = None if __opts__.get('ssh_use_home_key') and os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')): priv = os.path.expanduser('~/.ssh/id_rsa') else: priv = __opts__.get( ...
cast the value depending on the terraform type
def _cast_output_to_type(value, typ): '''cast the value depending on the terraform type''' if typ == 'b': return bool(value) if typ == 'i': return int(value) return value
Parses the terraform state file passing different resource types to the right handler
def _parse_state_file(state_file_path='terraform.tfstate'): ''' Parses the terraform state file passing different resource types to the right handler ''' ret = {} with salt.utils.files.fopen(state_file_path, 'r') as fh_: tfstate = salt.utils.json.load(fh_) modules = tfstate.get('modules...
Returns the roster from the terraform state file checks opts for location but defaults to terraform. tfstate
def targets(tgt, tgt_type='glob', **kwargs): # pylint: disable=W0613 ''' Returns the roster from the terraform state file, checks opts for location, but defaults to terraform.tfstate ''' roster_file = os.path.abspath('terraform.tfstate') if __opts__.get('roster_file'): roster_file = os.path...
Set the sleep timeouts of specific items such as disk monitor etc.
def set_timeout(name, value, power='ac', scheme=None): ''' Set the sleep timeouts of specific items such as disk, monitor, etc. Args: name (str) The setting to change, can be one of the following: - ``monitor`` - ``disk`` - ``standby`` ...
Resolves the master_ip and master_uri options
def resolve_dns(opts, fallback=True): ''' Resolves the master_ip and master_uri options ''' ret = {} check_dns = True if (opts.get('file_client', 'remote') == 'local' and not opts.get('use_master_when_local', False)): check_dns = False # Since salt.log is imported below, ...
parse host: port values from opts [ master ] and return valid: master: ip address or hostname as a string master_port: ( optional ) master returner port as integer
def prep_ip_port(opts): ''' parse host:port values from opts['master'] and return valid: master: ip address or hostname as a string master_port: (optional) master returner port as integer e.g.: - master: 'localhost:1234' -> {'master': 'localhost', 'master_port': 1234} - master: ...
Given the cache directory return the directory that process data is stored in creating it if it doesn t exist. The following optional Keyword Arguments are handled:
def get_proc_dir(cachedir, **kwargs): ''' Given the cache directory, return the directory that process data is stored in, creating it if it doesn't exist. The following optional Keyword Arguments are handled: mode: which is anything os.makedir would accept as mode. uid: the uid to set, if not ...
Detect the args and kwargs that need to be passed to a function call and check them against what was passed.
def load_args_and_kwargs(func, args, data=None, ignore_invalid=False): ''' Detect the args and kwargs that need to be passed to a function call, and check them against what was passed. ''' argspec = salt.utils.args.get_function_argspec(func) _args = [] _kwargs = {} invalid_kwargs = [] ...
Evaluate master function if master type is func and save it result in opts [ master ]
def eval_master_func(opts): ''' Evaluate master function if master type is 'func' and save it result in opts['master'] ''' if '__master_func_evaluated' not in opts: # split module and function and try loading the module mod_fun = opts['master'] mod, fun = mod_fun.split('.') ...
Centralized master event function which will return event type based on event_map
def master_event(type, master=None): ''' Centralized master event function which will return event type based on event_map ''' event_map = {'connected': '__master_connected', 'disconnected': '__master_disconnected', 'failback': '__master_failback', 'ali...
Evaluate all of the configured beacons grab the config again in case the pillar or grains changed
def process_beacons(self, functions): ''' Evaluate all of the configured beacons, grab the config again in case the pillar or grains changed ''' if 'config.merge' in functions: b_conf = functions['config.merge']('beacons', self.opts['beacons'], omit_opts=True) ...
Evaluates and returns a tuple of the current master address and the pub_channel.
def eval_master(self, opts, timeout=60, safe=True, failed=False, failback=False): ''' Evaluates and returns a tuple of the current master address and the pub_channel. In standard mode, just creat...
Discover master ( s ) and decide where to connect if SSDP is around. This modifies the configuration on the fly.: return:
def _discover_masters(self): ''' Discover master(s) and decide where to connect, if SSDP is around. This modifies the configuration on the fly. :return: ''' if self.opts['master'] == DEFAULT_MINION_OPTS['master'] and self.opts['discovery'] is not False: master...
Based on the minion configuration either return a randomized timer or just return the value of the return_retry_timer.
def _return_retry_timer(self): ''' Based on the minion configuration, either return a randomized timer or just return the value of the return_retry_timer. ''' msg = 'Minion return retry timer set to %s seconds' if self.opts.get('return_retry_timer_max'): try: ...
Tell the minion to reload the execution modules
def gen_modules(self, initial_load=False): ''' Tell the minion to reload the execution modules CLI Example: .. code-block:: bash salt '*' sys.reload_modules ''' self.opts['pillar'] = salt.pillar.get_pillar( self.opts, self.opts['grai...
Tell the minion to reload the execution modules
def gen_modules(self, initial_load=False): ''' Tell the minion to reload the execution modules CLI Example: .. code-block:: bash salt '*' sys.reload_modules ''' self.utils = salt.loader.utils(self.opts) self.functions = salt.loader.minion_mods( ...
Helper function to return the correct type of object
def _create_minion_object(self, opts, timeout, safe, io_loop=None, loaded_base_name=None, jid_queue=None): ''' Helper function to return the correct type of object ''' return Minion(opts, timeout, ...
Spawn all the coroutines which will sign in to masters
def _spawn_minions(self, timeout=60): ''' Spawn all the coroutines which will sign in to masters ''' # Run masters discovery over SSDP. This may modify the whole configuration, # depending of the networking and sets of masters. If match is 'any' we let # eval_master handl...
Create a minion and asynchronously connect it to a master
def _connect_minion(self, minion): ''' Create a minion, and asynchronously connect it to a master ''' auth_wait = minion.opts['acceptance_wait_time'] failed = False while True: if failed: if auth_wait < self.max_auth_wait: a...
Block until we are connected to a master
def sync_connect_master(self, timeout=None, failed=False): ''' Block until we are connected to a master ''' self._sync_connect_master_success = False log.debug("sync_connect_master") def on_connect_master_future_done(future): self._sync_connect_master_success...
Return a future which will complete when you are connected to a master
def connect_master(self, failed=False): ''' Return a future which will complete when you are connected to a master ''' master, self.pub_channel = yield self.eval_master(self.opts, self.timeout, self.safe, failed) yield self._post_master_init(master)
Function to finish init after connecting to a master
def _post_master_init(self, master): ''' Function to finish init after connecting to a master This is primarily loading modules, pillars, etc. (since they need to know which master they connected to) If this function is changed, please check ProxyMinion._post_master_init ...
Returns a copy of the opts with key bits stripped out
def _prep_mod_opts(self): ''' Returns a copy of the opts with key bits stripped out ''' mod_opts = {} for key, val in six.iteritems(self.opts): if key == 'logger': continue mod_opts[key] = val return mod_opts
Return the functions and the returners loaded up from the loader module
def _load_modules(self, force_refresh=False, notify=False, grains=None, opts=None): ''' Return the functions and the returners loaded up from the loader module ''' opt_in = True if not opts: opts = self.opts opt_in = False # if this is a *n...
Fire an event on the master or drop message if unable to send.
def _fire_master(self, data=None, tag=None, events=None, pretag=None, timeout=60, sync=True, timeout_handler=None): ''' Fire an event on the master, or drop message if unable to send. ''' load = {'id': self.opts['id'], 'cmd': '_minion_event', 'pretag': pre...
Return a single context manager for the minion s data
def ctx(self): ''' Return a single context manager for the minion's data ''' if six.PY2: return contextlib.nested( self.functions.context_dict.clone(), self.returners.context_dict.clone(), self.executors.context_dict.clone(), ...
This method should be used as a threading target start the actual minion side execution.
def _thread_return(cls, minion_instance, opts, data): ''' This method should be used as a threading target, start the actual minion side execution. ''' fn_ = os.path.join(minion_instance.proc_dir, data['jid']) if opts['multiprocessing'] and not salt.utils.platform.is_win...
This method should be used as a threading target start the actual minion side execution.
def _thread_multi_return(cls, minion_instance, opts, data): ''' This method should be used as a threading target, start the actual minion side execution. ''' fn_ = os.path.join(minion_instance.proc_dir, data['jid']) if opts['multiprocessing'] and not salt.utils.platform....
Return the data from the executed command to the master server
def _return_pub_multi(self, rets, ret_cmd='_return', timeout=60, sync=True): ''' Return the data from the executed command to the master server ''' if not isinstance(rets, list): rets = [rets] jids = {} for ret in rets: jid = ret.get('jid', ret.get...
Execute a state run based on information set in the minion config file
def _state_run(self): ''' Execute a state run based on information set in the minion config file ''' if self.opts['startup_states']: if self.opts.get('master_type', 'str') == 'disable' and \ self.opts.get('file_client', 'remote') == 'remote': ...