text
stringlengths
81
112k
Which machines does the hypervisor have @param kwargs: Passed to vb_xpcom_to_attribute_dict to filter the attributes @type kwargs: dict @return: Untreated dicts of the machines known to the hypervisor @rtype: [{}] def vb_list_machines(**kwargs): ''' Which machines does the hypervisor have @...
Creates a machine on the virtualbox hypervisor TODO pass more params to customize machine creation @param name: @type name: str @return: Representation of the created machine @rtype: dict def vb_create_machine(name=None): ''' Creates a machine on the virtualbox hypervisor TODO pass mo...
Tells virtualbox to create a VM by cloning from an existing one @param name: Name for the new VM @type name: str @param clone_from: @type clone_from: str @param timeout: maximum time in milliseconds to wait or -1 to wait indefinitely @type timeout: int @return dict of resulting VM def vb_c...
Helper to try and start machines @param machine: @type machine: IMachine @param session: @type session: ISession @return: @rtype: IProgress or None def _start_machine(machine, session): ''' Helper to try and start machines @param machine: @type machine: IMachine @param ses...
Tells Virtualbox to start up a VM. Blocking function! @param name: @type name: str @param timeout: Maximum time in milliseconds to wait or -1 to wait indefinitely @type timeout: int @return untreated dict of started VM def vb_start_vm(name=None, timeout=10000, **kwargs): ''' Tells Virt...
Tells Virtualbox to stop a VM. This is a blocking function! @param name: @type name: str @param timeout: Maximum time in milliseconds to wait or -1 to wait indefinitely @type timeout: int @return untreated dict of stopped VM def vb_stop_vm(name=None, timeout=10000, **kwargs): ''' Tells...
Attempts to get rid of a machine and all its files from the hypervisor @param name: @type name: str @param timeout int timeout in milliseconds def vb_destroy_machine(name=None, timeout=10000): ''' Attempts to get rid of a machine and all its files from the hypervisor @param name: @type name...
Attempts to build a dict from an XPCOM object. Attributes that don't exist in the object return an empty string. attribute_list = list of str or tuple(str,<a class>) e.g attributes=[('bad_attribute', list)] --> { 'bad_attribute': [] } @param xpcom: @type xpcom: @param interface_name: Which in...
Make machine presentable for outside world. !!!Modifies the input machine!!! @param machine: @type machine: dict @return: the modified input machine @rtype: dict def treat_machine_dict(machine): ''' Make machine presentable for outside world. !!!Modifies the input machine!!! @pa...
Checks in with the hypervisor to see if the machine with the given name is known @param name: @type name: @return: @rtype: def vb_machine_exists(name): ''' Checks in with the hypervisor to see if the machine with the given name is known @param name: @type name: @return: @rtype: ...
Attempts to fetch a machine from Virtualbox and convert it to a dict @param name: The unique name of the machine @type name: @param kwargs: To be passed to vb_xpcom_to_attribute_dict @type kwargs: @return: @rtype: dict def vb_get_machine(name, **kwargs): ''' Attempts to fetch a machine...
Compare before and after results from various salt functions, returning a dict describing the changes that were made. def compare_dicts(old=None, new=None): ''' Compare before and after results from various salt functions, returning a dict describing the changes that were made. ''' ret = {} ...
Compare before and after results from various salt functions, returning a dict describing the changes that were made def compare_lists(old=None, new=None): ''' Compare before and after results from various salt functions, returning a dict describing the changes that were made ''' ret = dict() ...
Generic function which will decode whichever type is passed, if necessary. Optionally use to_str=True to ensure strings are str types and not unicode on Python 2. If `strict` is True, and `keep` is False, and we fail to decode, a UnicodeDecodeError will be raised. Passing `keep` as True allows for the ...
Decode all string values to Unicode. Optionally use to_str=True to ensure strings are str types and not unicode on Python 2. def decode_dict(data, encoding=None, errors='strict', keep=False, normalize=False, preserve_dict_class=False, preserve_tuples=False, to_str=False): ''' ...
Decode all string values to Unicode. Optionally use to_str=True to ensure strings are str types and not unicode on Python 2. def decode_tuple(data, encoding=None, errors='strict', keep=False, normalize=False, preserve_dict_class=False, to_str=False): ''' Decode all string values to Unicode...
Generic function which will encode whichever type is passed, if necessary If `strict` is True, and `keep` is False, and we fail to encode, a UnicodeEncodeError will be raised. Passing `keep` as True allows for the original value to silently be returned in cases where encoding fails. This can be useful ...
Encode all string values to bytes def encode_dict(data, encoding=None, errors='strict', keep=False, preserve_dict_class=False, preserve_tuples=False): ''' Encode all string values to bytes ''' rv = data.__class__() if preserve_dict_class else {} for key, value in six.iteritems(data)...
Encode all string values to bytes def encode_list(data, encoding=None, errors='strict', keep=False, preserve_dict_class=False, preserve_tuples=False): ''' Encode all string values to bytes ''' rv = [] for item in data: if isinstance(item, list): item = encode_lis...
Encode all string values to Unicode def encode_tuple(data, encoding=None, errors='strict', keep=False, preserve_dict_class=False): ''' Encode all string values to Unicode ''' return tuple( encode_list(data, encoding, errors, keep, preserve_dict_class, True))
Common code to filter data structures like grains and pillar def filter_by(lookup_dict, lookup, traverse, merge=None, default='default', base=None): ''' Common code to filter data structures like grains and pillar ''' ret = None ...
Traverse a dict using a colon-delimited (or otherwise delimited, using the 'delimiter' param) target string. The target 'foo:bar:baz' will return data['foo']['bar']['baz'] if this value exists, and will otherwise return the dict in the default argument. def traverse_dict(data, key, default=None, delimiter=...
Traverse a dict or list using a colon-delimited (or otherwise delimited, using the 'delimiter' param) target string. The target 'foo:bar:0' will return data['foo']['bar'][0] if this value exists, and will otherwise return the dict in the default argument. Function will automatically determine the target...
Check for a match in a dictionary using a delimiter character to denote levels of subdicts, and also allowing the delimiter character to be matched. Thus, 'foo:bar:baz' will match data['foo'] == 'bar:baz' and data['foo']['bar'] == 'baz'. The latter would take priority over the former, as more deeply-nes...
Returns True if data is a list of one-element dicts (as found in many SLS schemas), otherwise returns False def is_dictlist(data): ''' Returns True if data is a list of one-element dicts (as found in many SLS schemas), otherwise returns False ''' if isinstance(data, list): for element i...
Takes a list of one-element dicts (as found in many SLS schemas) and repacks into a single dictionary. def repack_dictlist(data, strict=False, recurse=False, key_cb=None, val_cb=None): ''' Takes a list of one-element dicts (as ...
Test if an object is iterable, but not a string type. Test if an object is an iterator or is iterable itself. By default this does not return True for string objects. The `ignore` argument defaults to a list of string types that are not considered iterable. This can be used to also exclude things like...
Returns a boolean value representing the "truth" of the value passed. The rules for what is a "True" value are: 1. Integer/float values greater than 0 2. The string values "True" and "true" 3. Any object for which bool(obj) returns True def is_true(value=None): ''' Returns a boolea...
Convert MySQL-style output to a python dictionary def mysql_to_dict(data, key): ''' Convert MySQL-style output to a python dictionary ''' ret = {} headers = [''] for line in data: if not line: continue if line.startswith('+'): continue comps = lin...
Convert the data list, dictionary into simple types, i.e., int, float, string, bool, etc. def simple_types_filter(data): ''' Convert the data list, dictionary into simple types, i.e., int, float, string, bool, etc. ''' if data is None: return data simpletypes_keys = (six.string_typ...
Given an iterable, returns its items as a list, with any non-string items converted to unicode strings. def stringify(data): ''' Given an iterable, returns its items as a list, with any non-string items converted to unicode strings. ''' ret = [] for item in data: if six.PY2 and isin...
Query data using JMESPath language (http://jmespath.org). def json_query(data, expr): ''' Query data using JMESPath language (http://jmespath.org). ''' if jmespath is None: err = 'json_query requires jmespath module installed' log.error(err) raise RuntimeError(err) return jm...
Helper function for filter_falsey to determine if something is not to be considered falsey. :param any value: The value to consider :param list ignore_types: The types to ignore when considering the value. :return bool def _is_not_considered_falsey(value, ignore_types=()): ''' Helper function...
Helper function to remove items from an iterable with falsey value. Removes ``None``, ``{}`` and ``[]``, 0, '' (but does not remove ``False``). Recurses into sub-iterables if ``recurse`` is set to ``True``. :param dict/list data: Source iterable (dict, OrderedDict, list, set, ...) to process. :param in...
Returns a generator iterating over keys and values, with the keys all being lowercase. def items_lower(self): ''' Returns a generator iterating over keys and values, with the keys all being lowercase. ''' return ((key, val[1]) for key, val in six.iteritems(self._data))
Write a default to the system name The key of the given domain to write to domain The name of the domain to write to value The value to write to the given key vtype The type of value to be written, valid types are string, data, int[eger], float, bool[ean], dat...
Make sure the defaults value is absent name The key of the given domain to remove domain The name of the domain to remove from user The user to write the defaults to def absent(name, domain, user=None): ''' Make sure the defaults value is absent name The key ...
Return information for the specified user This is just returns dummy data so that salt states can work. :param str name: The name of the user account to show. CLI Example: .. code-block:: bash salt '*' shadow.info root def info(name): ''' Return information for the specified user ...
Converts the dotted notation of a saltclass class to its possible file counterparts. :param str _class: Dotted notation of the class :param str saltclass_path: Root to saltclass storage :return: 3-tuple of possible file counterparts :rtype: tuple(str) def get_class_paths(_class, saltclass_path): '...
Converts the absolute path to a saltclass file back to the dotted notation. .. code-block:: python print(get_class_from_file('/srv/saltclass/classes/services/nginx/init.yml', '/srv/saltclass')) # services.nginx :param str _file: Absolute path to file :param str saltclass_path: Root to saltc...
Takes a class name possibly including `*` or `?` wildcards (or any other wildcards supportet by `glob.glob`) and returns a list of expanded class names without wildcards. .. code-block:: python classes = match_class_glob('services.*', '/srv/saltclass') print(classes) # services.mariadb ...
Expand the list of `classes` to no longer include any globbing. :param iterable(str) classes: Iterable of classes :param dict salt_data: configuration data :return: Expanded list of classes with resolved globbing :rtype: list(str) def expand_classes_glob(classes, salt_data): ''' Expand the lis...
Returns True, if the given parameter value is an instance of either int, str, float or bool. def _is_simple_type(value): ''' Returns True, if the given parameter value is an instance of either int, str, float or bool. ''' return isinstance(value, six.string_types) or isinstance(value, int) or i...
Returns the type, id and option of a configuration object. def _get_type_id_options(name, configuration): ''' Returns the type, id and option of a configuration object. ''' # it's in a form of source.name if '.' in name: type_, sep, id_ = name.partition('.') options = configuration ...
Returns the only one key and it's value from a dictionary. def _expand_one_key_dictionary(_dict): ''' Returns the only one key and it's value from a dictionary. ''' key = next(six.iterkeys(_dict)) value = _dict[key] return key, value
Creates Arguments in a TypedParametervalue. def _parse_typed_parameter_typed_value(values): ''' Creates Arguments in a TypedParametervalue. ''' type_, value = _expand_one_key_dictionary(values) _current_parameter_value.type = type_ if _is_simple_type(value): arg = Argument(value) ...
Parses a TypedParameter and fills it with values. def _parse_typed_parameter(param): ''' Parses a TypedParameter and fills it with values. ''' global _current_parameter_value type_, value = _expand_one_key_dictionary(param) _current_parameter.type = type_ if _is_simple_type(value) and valu...
Parses the configuration and creates Parameter instances. def _create_and_add_parameters(params): ''' Parses the configuration and creates Parameter instances. ''' global _current_parameter if _is_simple_type(params): _current_parameter = SimpleParameter(params) _current_option.add_...
Parses the configuration and creates an Option instance. def _create_and_add_option(option): ''' Parses the configuration and creates an Option instance. ''' global _current_option _current_option = Option() type_, params = _expand_one_key_dictionary(option) _current_option.type = type_ ...
Return True, if arg is a reference to a previously defined statement. def _is_reference(arg): ''' Return True, if arg is a reference to a previously defined statement. ''' return isinstance(arg, dict) and len(arg) == 1 and isinstance(next(six.itervalues(arg)), six.string_types)
Return True, if arg is a junction statement. def _is_junction(arg): ''' Return True, if arg is a junction statement. ''' return isinstance(arg, dict) and len(arg) == 1 and next(six.iterkeys(arg)) == 'junction'
Adds a reference to statement. def _add_reference(reference, statement): ''' Adds a reference to statement. ''' type_, value = _expand_one_key_dictionary(reference) opt = Option(type_) param = SimpleParameter(value) opt.add_parameter(param) statement.add_child(opt)
Returns True, if arg is an inline definition of a statement. def _is_inline_definition(arg): ''' Returns True, if arg is an inline definition of a statement. ''' return isinstance(arg, dict) and len(arg) == 1 and isinstance(next(six.itervalues(arg)), list)
Adds an inline definition to statement. def _add_inline_definition(item, statement): ''' Adds an inline definition to statement. ''' global _current_statement backup = _current_statement type_, options = _expand_one_key_dictionary(item) _current_statement = UnnamedStatement(type=type_) ...
Adds a junction to the _current_statement. def _add_junction(item): ''' Adds a junction to the _current_statement. ''' type_, channels = _expand_one_key_dictionary(item) junction = UnnamedStatement(type='junction') for item in channels: type_, value = _expand_one_key_dictionary(item) ...
Parses a log path. def _parse_log_statement(options): ''' Parses a log path. ''' for i in options: if _is_reference(i): _add_reference(i, _current_statement) elif _is_junction(i): _add_junction(i) elif _is_inline_definition(i): _add_inline_def...
Build the configuration tree. The root object is _current_statement. def _build_config_tree(name, configuration): ''' Build the configuration tree. The root object is _current_statement. ''' type_, id_, options = _get_type_id_options(name, configuration) global _INDENT, _current_statement...
Builds syslog-ng configuration. This function is intended to be used from the state module, users should not use it directly! name : the id of the Salt document or it is the format of <statement name>.id config : the parsed YAML code write : if True, it writes the config into the configuration file, ...
Sets the path, where the syslog-ng binary can be found. This function is intended to be used from states. If syslog-ng is installed via a package manager, users don't need to use this function. CLI Example: .. code-block:: bash salt '*' syslog_ng.set_binary_path name=/usr/sbin def set_b...
Sets the configuration's name. This function is intended to be used from states. CLI Example: .. code-block:: bash salt '*' syslog_ng.set_config_file name=/etc/syslog-ng def set_config_file(name): ''' Sets the configuration's name. This function is intended to be used from states. ...
Runs the command cmd with options as its CLI parameters and returns the result as a dictionary. def _run_command(cmd, options=(), env=None): ''' Runs the command cmd with options as its CLI parameters and returns the result as a dictionary. ''' params = [cmd] params.extend(options) retu...
Sets variables. CLI Example: .. code-block:: bash salt '*' syslog_ng.set_parameters version='3.6' salt '*' syslog_ng.set_parameters binary_path=/home/user/install/syslog-ng/sbin config_file=/home/user/install/syslog-ng/etc/syslog-ng.conf def set_parameters(version=None, b...
Runs the specified command with the syslog_ng_sbin_dir in the PATH def _run_command_in_extended_path(syslog_ng_sbin_dir, command, params): ''' Runs the specified command with the syslog_ng_sbin_dir in the PATH ''' orig_path = os.environ.get('PATH', '') env = None if syslog_ng_sbin_dir: ...
Creates a dictionary from the parameters, which can be used to return data to Salt. def _format_return_data(retcode, stdout=None, stderr=None): ''' Creates a dictionary from the parameters, which can be used to return data to Salt. ''' ret = {'retcode': retcode} if stdout is not None: ...
Returns the version of the installed syslog-ng. If syslog_ng_sbin_dir is specified, it is added to the PATH during the execution of the command syslog-ng. CLI Example: .. code-block:: bash salt '*' syslog_ng.version salt '*' syslog_ng.version /home/user/install/syslog-ng/sbin def ver...
Returns the available modules. If syslog_ng_sbin_dir is specified, it is added to the PATH during the execution of the command syslog-ng. CLI Example: .. code-block:: bash salt '*' syslog_ng.modules salt '*' syslog_ng.modules /home/user/install/syslog-ng/sbin def modules(syslog_ng_sbin_d...
Returns statistics from the running syslog-ng instance. If syslog_ng_sbin_dir is specified, it is added to the PATH during the execution of the command syslog-ng-ctl. CLI Example: .. code-block:: bash salt '*' syslog_ng.stats salt '*' syslog_ng.stats /home/user/install/syslog-ng/sbin ...
Creates the state result dictionary. def _format_state_result(name, result, changes=None, comment=''): ''' Creates the state result dictionary. ''' if changes is None: changes = {'old': '', 'new': ''} return {'name': name, 'result': result, 'changes': changes, 'comment': comment...
Adds key and value as a command line parameter to params. def _add_cli_param(params, key, value): ''' Adds key and value as a command line parameter to params. ''' if value is not None: params.append('--{0}={1}'.format(key, value))
Adds key as a command line parameter to params. def _add_boolean_cli_param(params, key, value): ''' Adds key as a command line parameter to params. ''' if value is True: params.append('--{0}'.format(key))
Kills syslog-ng. This function is intended to be used from the state module. Users shouldn't use this function, if the service module is available on their system. If :mod:`syslog_ng.set_config_file <salt.modules.syslog_ng.set_binary_path>` is called before, this function will use the set binary path....
Ensures, that syslog-ng is started via the given parameters. This function is intended to be used from the state module. Users shouldn't use this function, if the service module is available on their system. If :mod:`syslog_ng.set_config_file <salt.modules.syslog_ng.set_binary_path>`, is called before,...
Reloads syslog-ng. This function is intended to be used from states. If :mod:`syslog_ng.set_config_file <salt.modules.syslog_ng.set_binary_path>`, is called before, this function will use the set binary path. CLI Example: .. code-block:: bash salt '*' syslog_ng.reload def reload_(name):...
Writes the given parameter config into the config file. This function is intended to be used from states. If :mod:`syslog_ng.set_config_file <salt.modules.syslog_ng.set_config_file>`, is called before, this function will use the set config file. CLI Example: .. code-block:: bash salt...
Writes the given parameter config into the config file. def _write_config(config, newlines=2): ''' Writes the given parameter config into the config file. ''' text = config if isinstance(config, dict) and len(list(list(config.keys()))) == 1: key = next(six.iterkeys(config)) text = c...
Removes the previous configuration file, then creates a new one and writes the name line. This function is intended to be used from states. If :mod:`syslog_ng.set_config_file <salt.modules.syslog_ng.set_config_file>`, is called before, this function will use the set config file. CLI Example: ...
Builds the body of a syslog-ng configuration object. def build_body(self): ''' Builds the body of a syslog-ng configuration object. ''' _increase_indent() body_array = [x.build() for x in self.iterable] nl = '\n' if self.append_extra_newline else '' if len(self...
Builds the textual representation of the whole configuration object with it's children. def build(self): ''' Builds the textual representation of the whole configuration object with it's children. ''' header = self.build_header() body = self.build_body() ...
Get the 'System Locale' parameters from dbus def _parse_dbus_locale(): ''' Get the 'System Locale' parameters from dbus ''' bus = dbus.SystemBus() localed = bus.get_object('org.freedesktop.locale1', '/org/freedesktop/locale1') properties = dbus.Interface(localed, 'o...
Parse localectl status into a dict. :return: dict def _localectl_status(): ''' Parse localectl status into a dict. :return: dict ''' if salt.utils.path.which('localectl') is None: raise CommandExecutionError('Unable to find "localectl"') ret = {} locale_ctl_out = (__salt__['cmd...
Use systemd's localectl command to set the LANG locale parameter, making sure not to trample on other params that have been set. def _localectl_set(locale=''): ''' Use systemd's localectl command to set the LANG locale parameter, making sure not to trample on other params that have been set. ''' ...
Get the current system locale CLI Example: .. code-block:: bash salt '*' locale.get_locale def get_locale(): ''' Get the current system locale CLI Example: .. code-block:: bash salt '*' locale.get_locale ''' ret = '' lc_ctl = salt.utils.systemd.booted(__context...
Sets the current system locale CLI Example: .. code-block:: bash salt '*' locale.set_locale 'en_US.UTF-8' def set_locale(locale): ''' Sets the current system locale CLI Example: .. code-block:: bash salt '*' locale.set_locale 'en_US.UTF-8' ''' lc_ctl = salt.utils.s...
Check if a locale is available. .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' locale.avail 'en_US.UTF-8' def avail(locale): ''' Check if a locale is available. .. versionadded:: 2014.7.0 CLI Example: .. code-block:: bash salt '*' locale.av...
Generate a locale. Options: .. versionadded:: 2014.7.0 :param locale: Any locale listed in /usr/share/i18n/locales or /usr/share/i18n/SUPPORTED for Debian and Gentoo based distributions, which require the charmap to be specified as part of the locale when generating it. verbose ...
Parsing template def _parse_template(tmpl_str): ''' Parsing template ''' tmpl_str = tmpl_str.strip() if tmpl_str.startswith('{'): tpl = salt.utils.json.loads(tmpl_str) else: try: tpl = salt.utils.yaml.safe_load(tmpl_str) except salt.utils.yaml.YAMLError as ex...
Deploy stack with the specified properties name The name of the stack template File of template environment File of environment params Parameter dict used to create the stack poll Poll (in sec.) and report events until stack complete rollback ...
Ensure that the named stack is absent name The name of the stack to remove poll Poll(in sec.) and report events until stack complete timeout Stack creation timeout in minutes profile Profile to use def absent(name, poll=5, timeout=60, profile=None): ''' Ensur...
Grain for the minion username def _username(): ''' Grain for the minion username ''' if pwd: username = pwd.getpwuid(os.getuid()).pw_name else: username = getpass.getuser() return username
Grain for the minion groupname def _groupname(): ''' Grain for the minion groupname ''' if grp: try: groupname = grp.getgrgid(os.getgid()).gr_name except KeyError: groupname = '' else: groupname = '' return groupname
Unpackages a payload def unpackage(package_): ''' Unpackages a payload ''' return salt.utils.msgpack.loads(package_, use_list=True, _msgpack_module=msgpack)
Pass in the required arguments for a payload, the enc type and the cmd, then a list of keyword args to generate the body of the load dict. def format_payload(enc, **kwargs): ''' Pass in the required arguments for a payload, the enc type and the cmd, then a list of keyword args to generate the body of t...
Run the correct loads serialization format :param encoding: Useful for Python 3 support. If the msgpack data was encoded using "use_bin_type=True", this will differentiate between the 'bytes' type and the 'str' type by decoding contents...
Run the correct serialization to load a file def load(self, fn_): ''' Run the correct serialization to load a file ''' data = fn_.read() fn_.close() if data: if six.PY3: return self.loads(data, encoding='utf-8') else: ...
Run the correct dumps serialization format :param use_bin_type: Useful for Python 3 support. Tells msgpack to differentiate between 'str' and 'bytes' types by encoding them differently. Since this changes the wire protocol, ...
Serialize the correct data into the named file object def dump(self, msg, fn_): ''' Serialize the correct data into the named file object ''' if six.PY2: fn_.write(self.dumps(msg)) else: # When using Python 3, write files in such a way # that ...
Lazily create the socket. def socket(self): ''' Lazily create the socket. ''' if not hasattr(self, '_socket'): # create a new one self._socket = self.context.socket(zmq.REQ) if hasattr(zmq, 'RECONNECT_IVL_MAX'): self._socket.setsockopt...
delete socket if you have it def clear_socket(self): ''' delete socket if you have it ''' if hasattr(self, '_socket'): if isinstance(self.poller.sockets, dict): sockets = list(self.poller.sockets.keys()) for socket in sockets: ...
Takes two arguments, the encryption type and the base payload def send(self, enc, load, tries=1, timeout=60): ''' Takes two arguments, the encryption type and the base payload ''' payload = {'enc': enc} payload['load'] = load pkg = self.serial.dumps(payload) self...
Detect the encryption type based on the payload def send_auto(self, payload, tries=1, timeout=60): ''' Detect the encryption type based on the payload ''' enc = payload.get('enc', 'clear') load = payload.get('load', {}) return self.send(enc, load, tries, timeout)