Search is not available for this dataset
text
stringlengths
75
104k
def _resolve_image(ret, image, client_timeout): ''' Resolve the image ID and pull the image if necessary ''' image_id = __salt__['docker.resolve_image_id'](image) if image_id is False: if not __opts__['test']: # Image not pulled locally, so try pulling it try: ...
def running(name, image=None, skip_translate=None, ignore_collisions=False, validate_ip_addrs=True, force=False, watch_action='force', start=True, shutdown_timeout=None, client_timeout=salt.utils.docker.CLIENT_TI...
def run(name, image=None, onlyif=None, unless=None, creates=None, bg=False, failhard=True, replace=False, force=False, skip_translate=None, ignore_collisions=False, validate_ip_addrs=True, client_timeout=salt.utils.docker.CL...
def stopped(name=None, containers=None, shutdown_timeout=None, unpause=False, error_on_absent=True, **kwargs): ''' Ensure that a container (or containers) is stopped name Name or ID of the container containers Run this state o...
def absent(name, force=False): ''' Ensure that a container is absent name Name of the container force : False Set to ``True`` to remove the container even if it is running Usage Examples: .. code-block:: yaml mycontainer: docker_container.absent mu...
def mod_run_check(onlyif, unless, creates): ''' Execute the onlyif/unless/creates logic. Returns a result dict if any of the checks fail, otherwise returns True ''' cmd_kwargs = {'use_vt': False, 'bg': False} if onlyif is not None: if isinstance(onlyif, six.string_types): on...
def mod_watch(name, sfun=None, **kwargs): ''' The docker_container 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 sho...
def _cache_provider_details(conn=None): ''' Provide a place to hang onto results of --list-[locations|sizes|images] so we don't have to go out to the API and get them every time. ''' DETAILS['avail_locations'] = {} DETAILS['avail_sizes'] = {} DETAILS['avail_images'] = {} locations = avai...
def list_nodes(**kwargs): ''' Return basic data on nodes ''' ret = {} nodes = list_nodes_full() for node in nodes: ret[node] = {} for prop in 'id', 'image', 'size', 'state', 'private_ips', 'public_ips': ret[node][prop] = nodes[node][prop] return ret
def list_nodes_full(**kwargs): ''' Return all data on nodes ''' nodes = _query('server/list') ret = {} for node in nodes: name = nodes[node]['label'] ret[name] = nodes[node].copy() ret[name]['id'] = node ret[name]['image'] = nodes[node]['os'] ret[name]['s...
def destroy(name): ''' Remove a node from Vultr ''' node = show_instance(name, call='action') params = {'SUBID': node['SUBID']} result = _query('server/destroy', method='POST', decode=False, data=_urlencode(params)) # The return of a destroy call is empty in the case of a success. # Err...
def show_instance(name, call=None): ''' Show the details from the provider concerning an instance ''' if call != 'action': raise SaltCloudSystemExit( 'The show_instance action must be called with -a or --action.' ) nodes = list_nodes_full() # Find under which cloud s...
def _lookup_vultrid(which_key, availkey, keyname): ''' Helper function to retrieve a Vultr ID ''' if DETAILS == {}: _cache_provider_details() which_key = six.text_type(which_key) try: return DETAILS[availkey][which_key][keyname] except KeyError: return False
def create(vm_): ''' Create a single VM from a data dict ''' if 'driver' not in vm_: vm_['driver'] = vm_['provider'] private_networking = config.get_cloud_config_value( 'enable_private_network', vm_, __opts__, search_global=False, default=False, ) startup_script = config.ge...
def _query(path, method='GET', data=None, params=None, header_dict=None, decode=True): ''' Perform a query directly against the Vultr REST API ''' api_key = config.get_cloud_config_value( 'api_key', get_configured_provider(), __opts__, search_global=False, ) manag...
def ext_pillar(minion_id, pillar, function, **kwargs): ''' Grabs external pillar data based on configured function ''' if function.startswith('_') or function not in globals(): return {} # Call specified function to pull redis data return globals()[function](minion_id, pillar, **kwargs)
def key_value(minion_id, pillar, # pylint: disable=W0613 pillar_key='redis_pillar'): ''' Looks for key in redis matching minion_id, returns a structure based on the data type of the redis key. String for string type, dict for hash type and lists for lists, sets and sorted se...
def key_json(minion_id, pillar, # pylint: disable=W0613 pillar_key=None): ''' Pulls a string from redis and deserializes it from json. Deserialized dictionary data loaded directly into top level if pillar_key is not set. pillar_key Pillar key to return data into '...
def sync(): ''' Sync portage/overlay trees and update the eix database CLI Example: .. code-block:: bash salt '*' eix.sync ''' # Funtoo patches eix to use 'ego sync' if __grains__['os'] == 'Funtoo': cmd = 'eix-sync -q' else: cmd = 'eix-sync -q -C "--ask" -C "n"...
def add(name, gid=None, **kwargs): ''' Add the specified group CLI Example: .. code-block:: bash salt '*' group.add foo 3456 ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) if salt.utils.data.is_true(kwargs.pop('system', False)): log.warning('pw_group module does not s...
def adduser(name, username): ''' Add a user in the group. CLI Example: .. code-block:: bash salt '*' group.adduser foo bar Verifies if a valid username 'bar' as a member of an existing group 'foo', if not then adds it. ''' # Note: pw exits with code 65 if group is unknown ...
def deluser(name, username): ''' Remove a user from the group. CLI Example: .. code-block:: bash salt '*' group.deluser foo bar Removes a member user 'bar' from a group 'foo'. If group is not present then returns True. ''' grp_info = __salt__['group.info'](name) if user...
def datasource_exists(name, jboss_config, datasource_properties, recreate=False, profile=None): ''' Ensures that a datasource with given properties exist on the jboss instance. If datasource doesn't exist, it is created, otherwise only the properties that are different will be updated. name Dat...
def bindings_exist(name, jboss_config, bindings, profile=None): ''' Ensures that given JNDI binding are present on the server. If a binding doesn't exist on the server it will be created. If it already exists its value will be changed. jboss_config: Dict with connection properties (see stat...
def deployed(name, jboss_config, salt_source=None): '''Ensures that the given application is deployed on server. jboss_config: Dict with connection properties (see state description) salt_source: How to find the artifact to be deployed. target_file: Where to look...
def reloaded(name, jboss_config, timeout=60, interval=5): ''' Reloads configuration of jboss server. jboss_config: Dict with connection properties (see state description) timeout: Time to wait until jboss is back in running state. Default timeout is 60s. interval: Interval b...
def valid_username(user): ''' Validates a username based on the guidelines in `useradd(8)` ''' if not isinstance(user, six.string_types): return False if len(user) > 32: return False return VALID_USERNAME.match(user) is not None
def load_states(): ''' This loads our states into the salt __context__ ''' states = {} # the loader expects to find pillar & grain data __opts__['grains'] = salt.loader.grains(__opts__) __opts__['pillar'] = __pillar__ lazy_utils = salt.loader.utils(__opts__) lazy_funcs = salt.loader...
def send_message(url, message): ''' Send a message to the google chat room specified in the webhook url. .. code-block:: bash salt '*' google_chat.send_message "https://chat.googleapis.com/v1/spaces/example_space/messages?key=example_key" "This is a test message" ''' headers = {'Content-Ty...
def raise_error(name=None, args=None, message=''): ''' Raise an exception with __name__ from name, args from args If args is None Otherwise message from message\ If name is empty then use "Exception" ''' name = name or 'Exception' if hasattr(salt.exceptions, name): ex = getattr(salt....
def fire_exception(exc, opts, job=None, node='minion'): ''' Fire raw exception across the event bus ''' if job is None: job = {} event = salt.utils.event.SaltEvent(node, opts=opts, listen=False) event.fire_event(pack_exception(exc), '_salt_error')
def render(msgpack_data, saltenv='base', sls='', **kws): ''' Accepts a message pack string or a file object, renders said data back to a python dict. .. note: This renderer is NOT intended for use in creating sls files by hand, but exists to allow for data backends to serialize the high...
def init_git_pillar(opts): ''' Clear out the ext pillar caches, used when the master starts ''' ret = [] for opts_dict in [x for x in opts.get('ext_pillar', [])]: if 'git' in opts_dict: try: pillar = salt.utils.gitfs.GitPillar( opts, ...
def clean_fsbackend(opts): ''' Clean out the old fileserver backends ''' # Clear remote fileserver backend caches so they get recreated for backend in ('git', 'hg', 'svn'): if backend in opts['fileserver_backend']: env_cache = os.path.join( opts['cachedir'], ...
def clean_expired_tokens(opts): ''' Clean expired tokens from the master ''' loadauth = salt.auth.LoadAuth(opts) for tok in loadauth.list_tokens(): token_data = loadauth.get_tok(tok) if 'expire' not in token_data or token_data.get('expire', 0) < time.time(): loadauth.rm_t...
def clean_old_jobs(opts): ''' Clean out the old jobs from the job cache ''' # TODO: better way to not require creating the masterminion every time? mminion = salt.minion.MasterMinion( opts, states=False, rend=False, ) # If the maste...
def clean_proc_dir(opts): ''' Clean out old tracked jobs running on the master Generally, anything tracking a job should remove the job once the job has finished. However, this will remove any jobs that for some reason were not properly removed when finished or errored. ''' serial = sal...
def access_keys(opts): ''' A key needs to be placed in the filesystem with permissions 0400 so clients are required to run as root. ''' # TODO: Need a way to get all available users for systems not supported by pwd module. # For now users pattern matching will not work for publisher_acl. ...
def fileserver_update(fileserver): ''' Update the fileserver backends, requires that a salt.fileserver.Fileserver object be passed in ''' try: if not fileserver.servers: log.error( 'No fileservers loaded, the master will not be able to ' 'serve fil...
def check_permissions(self, filename): ''' Check if the specified filename has correct permissions ''' if salt.utils.platform.is_windows(): return True # After we've ascertained we're not on windows groups = salt.utils.user.get_gid_list(self.opts['user'], inc...
def check_signing_file(self, keyid, signing_file): ''' Check a keyid for membership in a signing file ''' if not signing_file or not os.path.exists(signing_file): return False if not self.check_permissions(signing_file): log.warning('Wrong permissions for...
def check_autosign_dir(self, keyid): ''' Check a keyid for membership in a autosign directory. ''' autosign_dir = os.path.join(self.opts['pki_dir'], 'minions_autosign') # cleanup expired files expire_minutes = self.opts.get('autosign_timeout', 120) if expire_minu...
def check_autosign_grains(self, autosign_grains): ''' Check for matching grains in the autosign_grains_dir. ''' if not autosign_grains or 'autosign_grains_dir' not in self.opts: return False autosign_grains_dir = self.opts['autosign_grains_dir'] for root, dir...
def check_autosign(self, keyid, autosign_grains=None): ''' Checks if the specified keyid should automatically be signed. ''' if self.opts['auto_accept']: return True if self.check_signing_file(keyid, self.opts.get('autosign_file', None)): return True ...
def __setup_fileserver(self): ''' Set the local file objects from the file server interface ''' fs_ = salt.fileserver.Fileserver(self.opts) self._serve_file = fs_.serve_file self._file_find = fs_._find_file self._file_hash = fs_.file_hash self._file_list =...
def __verify_minion_publish(self, load): ''' Verify that the passed information authorized a minion to execute ''' # Verify that the load is valid if 'peer' not in self.opts: return False if not isinstance(self.opts['peer'], dict): return False ...
def _master_opts(self, load): ''' Return the master options to the minion ''' mopts = {} file_roots = {} envs = self._file_envs() for saltenv in envs: if saltenv not in file_roots: file_roots[saltenv] = [] mopts['file_roots'] = ...
def _master_tops(self, load, skip_verify=False): ''' Return the results from master_tops if configured ''' if not skip_verify: if 'id' not in load: log.error('Received call for external nodes without an id') return {} if not salt.ut...
def _mine_get(self, load, skip_verify=False): ''' Gathers the data from the specified minions' mine ''' if not skip_verify: if any(key not in load for key in ('id', 'tgt', 'fun')): return {} if isinstance(load['fun'], six.string_types): fu...
def _mine(self, load, skip_verify=False): ''' Return the mine data ''' if not skip_verify: if 'id' not in load or 'data' not in load: return False if self.opts.get('minion_data_cache', False) or self.opts.get('enforce_mine_cache', False): c...
def _mine_delete(self, load): ''' Allow the minion to delete a specific function from its own mine ''' if 'id' not in load or 'fun' not in load: return False if self.opts.get('minion_data_cache', False) or self.opts.get('enforce_mine_cache', False): cbank ...
def _mine_flush(self, load, skip_verify=False): ''' Allow the minion to delete all of its own mine contents ''' if not skip_verify and 'id' not in load: return False if self.opts.get('minion_data_cache', False) or self.opts.get('enforce_mine_cache', False): ...
def _file_recv(self, load): ''' Allows minions to send files to the master, files are sent to the master file cache ''' if any(key not in load for key in ('id', 'path', 'loc')): return False if not self.opts['file_recv'] or os.path.isabs(load['path']): ...
def _pillar(self, load): ''' Return the pillar data for the minion ''' if any(key not in load for key in ('id', 'grains')): return False # pillar = salt.pillar.Pillar( log.debug('Master _pillar using ext: %s', load.get('ext')) pillar = salt.pillar.get_p...
def _minion_event(self, load): ''' Receive an event from the minion and fire it on the master event interface ''' if 'id' not in load: return False if 'events' not in load and ('tag' not in load or 'data' not in load): return False if 'even...
def _return(self, load): ''' Handle the return data sent from the minions ''' # Generate EndTime endtime = salt.utils.jid.jid_to_time(salt.utils.jid.gen_jid(self.opts)) # If the return data is invalid, just ignore it if any(key not in load for key in ('return', 'j...
def _syndic_return(self, load): ''' Receive a syndic minion return and format it to look like returns from individual minions. ''' # Verify the load if any(key not in load for key in ('return', 'jid', 'id')): return None # if we have a load, save it ...
def minion_runner(self, load): ''' Execute a runner from a minion, return the runner's function data ''' if 'peer_run' not in self.opts: return {} if not isinstance(self.opts['peer_run'], dict): return {} if any(key not in load for key in ('fun', '...
def pub_ret(self, load, skip_verify=False): ''' Request the return data from a specific jid, only allowed if the requesting minion also initialted the execution. ''' if not skip_verify and any(key not in load for key in ('jid', 'id')): return {} else: ...
def minion_pub(self, load): ''' Publish a command initiated from a minion, this method executes minion restrictions so that the minion publication will only work if it is enabled in the config. The configuration on the master allows minions to be matched to salt functions...
def minion_publish(self, load): ''' Publish a command initiated from a minion, this method executes minion restrictions so that the minion publication will only work if it is enabled in the config. The configuration on the master allows minions to be matched to salt funct...
def revoke_auth(self, load): ''' Allow a minion to request revocation of its own key ''' if 'id' not in load: return False keyapi = salt.key.Key(self.opts) keyapi.delete_key(load['id'], preserve_minions=load.get('preserve_minion_cache...
def runner(self, load): ''' Send a master control function back to the runner system ''' # All runner opts pass through eauth auth_type, err_name, key = self._prep_auth_info(load) # Authenticate auth_check = self.loadauth.check_authentication(load, auth_type) ...
def wheel(self, load): ''' Send a master control function back to the wheel system ''' # All wheel ops pass through eauth auth_type, err_name, key = self._prep_auth_info(load) # Authenticate auth_check = self.loadauth.check_authentication( load, ...
def mk_token(self, load): ''' Create and return an authentication token, the clear load needs to contain the eauth key and the needed authentication creds. ''' token = self.loadauth.mk_token(load) if not token: log.warning('Authentication failure of type "eaut...
def publish(self, load): ''' This method sends out publications to the minions, it can only be used by the LocalClient. ''' extra = load.get('kwargs', {}) publisher_acl = salt.acl.PublisherACL(self.opts['publisher_acl_blacklist']) if publisher_acl.user_is_blackl...
def start(token, control=False, trigger='!', groups=None, groups_pillar_name=None, fire_all=False, tag='salt/engines/slack'): ''' Listen to slack events and forward them to salt, new version ''' if (not token) or (not token.startswith('xoxb'))...
def get_slack_users(self, token): ''' Get all users from Slack ''' ret = salt.utils.slack.query(function='users', api_key=token, opts=__opts__) users = {} if 'message' in ret: for item ...
def get_slack_channels(self, token): ''' Get all channel names from Slack ''' ret = salt.utils.slack.query( function='rooms', api_key=token, # These won't be honored until https://github.com/saltstack/salt/pull/41187/files is merged opts={...
def get_config_groups(self, groups_conf, groups_pillar_name): ''' get info from groups in config, and from the named pillar todo: add specification for the minion to use to recover pillar ''' # Get groups # Default to returning something that'll never match ret_g...
def _groups_from_pillar(self, pillar_name): ''' pillar_prefix is the pillar.get syntax for the pillar to be queried. Group name is gotten via the equivalent of using ``salt['pillar.get']('{}:{}'.format(pillar_prefix, group_name))`` in a jinja template. returns a dictiona...
def fire(self, tag, msg): ''' This replaces a function in main called 'fire' It fires an event into the salt bus. ''' if __opts__.get('__role') == 'master': fire_master = salt.utils.event.get_master_event( __opts__, __opts__['sock_dir'...
def can_user_run(self, user, command, groups): ''' Break out the permissions into the following: Check whether a user is in any group, including whether a group has the '*' membership :type user: str :param user: The username being checked against :type command: str ...
def commandline_to_list(self, cmdline_str, trigger_string): ''' cmdline_str is the string of the command line trigger_string is the trigger string, to be removed ''' cmdline = salt.utils.args.shlex_split(cmdline_str[len(trigger_string):]) # Remove slack url parsing ...
def control_message_target(self, slack_user_name, text, loaded_groups, trigger_string): '''Returns a tuple of (target, cmdline,) for the response Raises IndexError if a user can't be looked up from all_slack_users Returns (False, False) if the user doesn't have permission These are re...
def message_text(self, m_data): ''' Raises ValueError if a value doesn't work out, and TypeError if this isn't a message type ''' if m_data.get('type') != 'message': raise TypeError('This is not a message') # Edited messages have text in message _text ...
def generate_triggered_messages(self, token, trigger_string, groups, groups_pillar_name): ''' slack_token = string trigger_string = string input_valid_users = set input_valid_commands = set When the trigger_string prefixes the message text, yields a dictionary of...
def get_target(self, permitted_group, cmdline, alias_cmdline): ''' When we are permitted to run a command on a target, look to see what the default targeting is for that group, and for that specific command (if provided). It's possible for None or False to be the result of eithe...
def format_return_text(self, data, function, **kwargs): # pylint: disable=unused-argument ''' Print out YAML using the block mode ''' # emulate the yaml_out output formatter. It relies on a global __opts__ object which # we can't obviously pass in try: try: ...
def parse_args_and_kwargs(self, cmdline): ''' cmdline: list returns tuple of: args (list), kwargs (dict) ''' # Parse args and kwargs args = [] kwargs = {} if len(cmdline) > 1: for item in cmdline[1:]: if '=' in item: ...
def get_jobs_from_runner(self, outstanding_jids): ''' Given a list of job_ids, return a dictionary of those job_ids that have completed and their results. Query the salt event bus via the jobs runner. jobs.list_job will show a job in progress, jobs.lookup_jid will return a job t...
def run_commands_from_slack_async(self, message_generator, fire_all, tag, control, interval=1): ''' Pull any pending messages from the message_generator, sending each one to either the event bus, the command_async or both, depending on the values of fire_all and command ''' ...
def run_command_async(self, msg): ''' :type message_generator: generator of dict :param message_generator: Generates messages from slack that should be run :type fire_all: bool :param fire_all: Whether to also fire messages to the event bus :type tag: str :para...
def _get_serv(ret=None, commit=False): ''' Return a Pg cursor ''' _options = _get_options(ret) try: conn = psycopg2.connect(host=_options.get('host'), user=_options.get('user'), password=_options.get('passwd'), ...
def returner(ret): ''' Return data to a postgres server ''' try: with _get_serv(ret, commit=True) as cur: sql = '''INSERT INTO salt_returns (fun, jid, return, id, success, full_ret) VALUES (%s, %s, %s, %s, %s, %s)''' cur.execute( ...
def get_jids(): ''' Return a list of all job ids ''' with _get_serv(ret=None, commit=True) as cur: sql = '''SELECT jid, load FROM jids''' cur.execute(sql) data = cur.fetchall() ret = {} for jid, load in data: ret[jid] = salt.utils.jid...
def present(name, **kwargs): ''' Ensures that the host group exists, eventually creates new host group. .. versionadded:: 2016.3.0 :param name: name of the host group :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connection_...
def absent(name, **kwargs): ''' Ensures that the host group does not exist, eventually delete host group. .. versionadded:: 2016.3.0 :param name: name of the host group :param _connection_user: Optional - zabbix user (can also be set in opts or pillar, see module's docstring) :param _connectio...
def _json_to_unicode(data): ''' Encode json values in unicode to match that of the API ''' ret = {} for key, value in data.items(): if not isinstance(value, six.text_type): if isinstance(value, dict): ret[key] = _json_to_unicode(value) else: ...
def _is_updated(old_conf, new_conf): ''' Compare the API results to the current statefile data ''' changed = {} # Dirty json hacking to get parameters in the same format new_conf = _json_to_unicode(salt.utils.json.loads( salt.utils.json.dumps(new_conf, ensure_ascii=False))) old_conf...
def _do_element_present(name, elem_type, data, server=None): ''' Generic function to create or update an element ''' ret = {'changes': {}, 'update': False, 'create': False, 'error': None} try: elements = __salt__['glassfish.enum_{0}'.format(elem_type)]() except requests.ConnectionError a...
def _do_element_absent(name, elem_type, data, server=None): ''' Generic function to delete an element ''' ret = {'delete': False, 'error': None} try: elements = __salt__['glassfish.enum_{0}'.format(elem_type)]() except requests.ConnectionError as error: if __opts__['test']: ...
def connection_factory_present(name, restype='connection_factory', description='', enabled=True, min_size=1, max_size=250, resize_quan...
def connection_factory_absent(name, both=True, server=None): ''' Ensures the transaction factory is absent. name Name of the connection factory both Delete both the pool and the resource, defaults to ``true`` ''' ret = {'name': name, 'result': None, 'comment': None, 'changes': ...
def destination_present(name, physical, restype='queue', description='', enabled=True, server=None): ''' Ensures that the JMS Destination Resource (queue or topic) is present name ...
def destination_absent(name, server=None): ''' Ensures that the JMS Destination doesn't exists name Name of the JMS Destination ''' ret = {'name': name, 'result': None, 'comment': None, 'changes': {}} jms_ret = _do_element_absent(name, 'admin_object_resource', {}, server) if not jms...
def jdbc_datasource_present(name, description='', enabled=True, restype='datasource', vendor='mysql', sql_url='', sql_user='', ...
def jdbc_datasource_absent(name, both=True, server=None): ''' Ensures the JDBC Datasource doesn't exists name Name of the datasource both Delete both the pool and the resource, defaults to ``true`` ''' ret = {'name': name, 'result': None, 'comment': None, 'changes': {}} pool...
def system_properties_present(server=None, **kwargs): ''' Ensures that the system properties are present properties The system properties ''' ret = {'name': '', 'result': None, 'comment': None, 'changes': {}} del kwargs['name'] try: data = __salt__['glassfish.get_system_pro...
def system_properties_absent(name, server=None): ''' Ensures that the system property doesn't exists name Name of the system property ''' ret = {'name': '', 'result': None, 'comment': None, 'changes': {}} try: data = __salt__['glassfish.get_system_properties'](server=server) ...