INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Ensures that the named configmap is absent from the given namespace.
def configmap_absent(name, namespace='default', **kwargs): ''' Ensures that the named configmap is absent from the given namespace. name The name of the configmap namespace The namespace holding the configmap. The 'default' one is going to be used unless a different one is spec...
Ensures that the named configmap is present inside of the specified namespace with the given data. If the configmap exists it will be replaced.
def configmap_present( name, namespace='default', data=None, source=None, template=None, **kwargs): ''' Ensures that the named configmap is present inside of the specified namespace with the given data. If the configmap exists it will be replaced. nam...
Ensures that the named pod is absent from the given namespace.
def pod_absent(name, namespace='default', **kwargs): ''' Ensures that the named pod is absent from the given namespace. name The name of the pod namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, 'comme...
Ensures that the named pod is present inside of the specified namespace with the given metadata and spec. If the pod exists it will be replaced.
def pod_present( name, namespace='default', metadata=None, spec=None, source='', template='', **kwargs): ''' Ensures that the named pod is present inside of the specified namespace with the given metadata and spec. If the pod exists it will be repl...
Ensures that the named label is absent from the node.
def node_label_absent(name, node, **kwargs): ''' Ensures that the named label is absent from the node. name The name of the label node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __...
Ensures the label folder doesn t exist on the specified node.
def node_label_folder_absent(name, node, **kwargs): ''' Ensures the label folder doesn't exist on the specified node. name The name of label folder node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''...
Ensures that the named label is set on the named node with the given value. If the label exists it will be replaced.
def node_label_present( name, node, value, **kwargs): ''' Ensures that the named label is set on the named node with the given value. If the label exists it will be replaced. name The name of the label. value Value of the label. node ...
This function gets called when the proxy starts up. For login the protocol and port are cached.
def init(opts): ''' This function gets called when the proxy starts up. For login the protocol and port are cached. ''' log.debug('Initting esxvm proxy module in process %s', os.getpid()) log.debug('Validating esxvm proxy input') proxy_conf = merge(opts.get('proxy', {}), __pillar__.get('prox...
Cycle through all the possible credentials and return the first one that works.
def find_credentials(): ''' Cycle through all the possible credentials and return the first one that works. ''' # if the username and password were already found don't go through the # connection process again if 'username' in DETAILS and 'password' in DETAILS: return DETAILS['usern...
Device - Mapper Multipath flush
def multipath_flush(device): ''' Device-Mapper Multipath flush CLI Example: .. code-block:: bash salt '*' devmap.multipath_flush mpath1 ''' if not os.path.exists(device): return '{0} does not exist'.format(device) cmd = 'multipath -f {0}'.format(device) return __salt_...
Set debconf selections from a file or a template
def set_file(name, source, template=None, context=None, defaults=None, **kwargs): ''' Set debconf selections from a file or a template .. code-block:: yaml <state_id>: debconf.set_file: - source: salt://pathto/pkg.selections <state_id>: debconf.set_file: ...
Set debconf selections
def set(name, data, **kwargs): ''' Set debconf selections .. code-block:: yaml <state_id>: debconf.set: - name: <name> - data: <question>: {'type': <type>, 'value': <value>} <question>: {'type': <type>, 'value': <value>} <s...
Scan for Docker events and fire events
def start(docker_url='unix://var/run/docker.sock', timeout=CLIENT_TIMEOUT, tag='salt/engines/docker_events', filters=None): ''' Scan for Docker events and fire events Example Config .. code-block:: yaml engines: - docker_events: docker_url...
Return configuration user passed api_opts override salt config. get vars
def _get_config(**api_opts): ''' Return configuration user passed api_opts override salt config.get vars ''' config = { 'api_sslverify': True, 'api_url': 'https://INFOBLOX/wapi/v1.2.1', 'api_user': '', 'api_key': '', } if '__salt__' in globals(): confi...
Update host record. This is a helper call to update_object.
def update_host(name, data, **api_opts): ''' Update host record. This is a helper call to update_object. Find a hosts ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_host name=fqdn data={} ''' o = get_host(name=na...
Update raw infoblox object. This is a low level api call.
def update_object(objref, data, **api_opts): ''' Update raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object objref=[ref_of_object] data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Wo...
Delete infoblox object. This is a low level api call.
def delete_object(objref, **api_opts): ''' Delete infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.delete_object objref=[ref_of_object] ''' if '__opts__' in globals() and __opts__['test']: return {'Test': 'Would attempt to del...
Create raw infoblox object. This is a low level api call.
def create_object(object_type, data, **api_opts): ''' Create raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.update_object object_type=record:host data={} ''' if '__opts__' in globals() and __opts__['test']: return {'Tes...
Get raw infoblox object. This is a low level api call.
def get_object(objref, data=None, return_fields=None, max_results=None, ensure_none_or_one_result=False, **api_opts): ''' Get raw infoblox object. This is a low level api call. CLI Example: .. code-block:: bash salt-call infoblox.get_object objref=[_ref of object] ''' i...
Create a cname record.
def create_cname(data, **api_opts): ''' Create a cname record. CLI Example: .. code-block:: bash salt-call infoblox.create_cname data={ \ "comment": "cname to example server", \ "name": "example.example.com", \ "zone": "example.com", \ "view": "...
Get CNAME information.
def get_cname(name=None, canonical=None, return_fields=None, **api_opts): ''' Get CNAME information. CLI Examples: .. code-block:: bash salt-call infoblox.get_cname name=example.example.com salt-call infoblox.get_cname canonical=example-ha-0.example.com ''' infoblox = _get_inf...
Update CNAME. This is a helper call to update_object.
def update_cname(name, data, **api_opts): ''' Update CNAME. This is a helper call to update_object. Find a CNAME ``_ref`` then call update_object with the record data. CLI Example: .. code-block:: bash salt-call infoblox.update_cname name=example.example.com data="{ 'cano...
Delete CNAME. This is a helper call to delete_object.
def delete_cname(name=None, canonical=None, **api_opts): ''' Delete CNAME. This is a helper call to delete_object. If record is not found, return True CLI Examples: .. code-block:: bash salt-call infoblox.delete_cname name=example.example.com salt-call infoblox.delete_cname canon...
Get host information
def get_host(name=None, ipv4addr=None, mac=None, return_fields=None, **api_opts): ''' Get host information CLI Examples: .. code-block:: bash salt-call infoblox.get_host hostname.domain.ca salt-call infoblox.get_host ipv4addr=123.123.122.12 salt-call infoblox.get_host mac=00:5...
Get all host information
def get_host_advanced(name=None, ipv4addr=None, mac=None, **api_opts): ''' Get all host information CLI Example: .. code-block:: bash salt-call infoblox.get_host_advanced hostname.domain.ca ''' infoblox = _get_infoblox(**api_opts) host = infoblox.get_host_advanced(name=name, mac=m...
Get host domain name
def get_host_domainname(name, domains=None, **api_opts): ''' Get host domain name If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is returned. If none are found the return is None ...
Get hostname
def get_host_hostname(name, domains=None, **api_opts): ''' Get hostname If no domains are passed, the hostname is checked for a zone in infoblox, if no zone split on first dot. If domains are provided, the best match out of the list is truncated from the fqdn leaving the hostname. If no m...
Get mac address from host record.
def get_host_mac(name=None, allow_array=False, **api_opts): ''' Get mac address from host record. Use `allow_array` to return possible multiple values. CLI Example: .. code-block:: bash salt-call infoblox.get_host_mac host=localhost.domain.com ''' data = get_host(name=name, **api...
Get ipv4 address from host record.
def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get...
Get host ipv4addr information
def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4a...
Get host ipv6addr information
def get_host_ipv6addr_info(ipv6addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv6addr information CLI Example: .. code-block:: bash salt-call infoblox.get_host_ipv6addr_i...
Get list of all networks. This is helpful when looking up subnets to use with func: nextavailableip
def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts): ''' Get list of all networks. This is helpful when looking up subnets to use with func:nextavailableip This call is offen slow and not cached! some return_fields comment,network,network_view,ddns_domainname,disable,e...
Delete host
def delete_host(name=None, mac=None, ipv4addr=None, **api_opts): ''' Delete host CLI Example: .. code-block:: bash salt-call infoblox.delete_host name=example.domain.com salt-call infoblox.delete_host ipv4addr=123.123.122.12 salt-call infoblox.delete_host ipv4addr=123.123.122....
Get ip range
def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts): ''' Get ip range CLI Example: .. code-block:: bash salt-call infoblox.get_ipv4_range start_addr=123.123.122.12 ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_range(start_addr, end_add...
Delete ip range.
def delete_ipv4_range(start_addr=None, end_addr=None, **api_opts): ''' Delete ip range. CLI Example: .. code-block:: bash salt-call infoblox.delete_ipv4_range start_addr=123.123.122.12 ''' r = get_ipv4_range(start_addr, end_addr, **api_opts) if r: return delete_object(r['_...
Get A record
def get_a(name=None, ipv4addr=None, allow_array=True, **api_opts): ''' Get A record CLI Examples: .. code-block:: bash salt-call infoblox.get_a name=abc.example.com salt-call infoblox.get_a ipv4addr=192.168.3.5 ''' data = {} if name: data['name'] = name if ipv4...
Delete A record
def delete_a(name=None, ipv4addr=None, allow_array=False, **api_opts): ''' Delete A record If the A record is used as a round robin you can set ``allow_array=True`` to delete all records for the hostname. CLI Examples: .. code-block:: bash salt-call infoblox.delete_a name=abc.example...
Ensure infoblox A record.
def present(name=None, ipv4addr=None, data=None, ensure_data=True, **api_opts): ''' Ensure infoblox A record. When you wish to update a hostname ensure `name` is set to the hostname of the current record. You can give a new name in the `data.name`. State example: .. code-block:: yaml ...
Ensure infoblox A record is removed.
def absent(name=None, ipv4addr=None, **api_opts): ''' Ensure infoblox A record is removed. State example: .. code-block:: yaml infoblox_a.absent: - name: example-ha-0.domain.com infoblox_a.absent: - name: - ipv4addr: 127.0.23.23 ''' ret = {...
Get the kapacitor URL.
def _get_url(): ''' Get the kapacitor URL. ''' protocol = __salt__['config.option']('kapacitor.protocol', 'http') host = __salt__['config.option']('kapacitor.host', 'localhost') port = __salt__['config.option']('kapacitor.port', 9092) return '{0}://{1}:{2}'.format(protocol, host, port)
Get a dict of data on a task.
def get_task(name): ''' Get a dict of data on a task. name Name of the task to get information about. CLI Example: .. code-block:: bash salt '*' kapacitor.get_task cpu ''' url = _get_url() if version() < '0.13': task_url = '{0}/task?name={1}'.format(url, name...
Run a Kapacitor task and return a dictionary of info.
def _run_cmd(cmd): ''' Run a Kapacitor task and return a dictionary of info. ''' ret = {} env_vars = { 'KAPACITOR_URL': _get_url(), 'KAPACITOR_UNSAFE_SSL': __salt__['config.option']('kapacitor.unsafe_ssl', 'false'), } result = __salt__['cmd.run_all'](cmd, env=env_vars) i...
Define a task. Serves as both create/ update.
def define_task(name, tick_script, task_type='stream', database=None, retention_policy='default', dbrps=None): ''' Define a task. Serves as both create/update. name Name of the task. tick_script Path to the...
Parse output from ip a
def _ip_ifaces(): ''' Parse output from 'ip a' ''' tmp = {} ret = {} if_ = None at_ = None out = __salt__['cmd.run']('ip a') for line in out.splitlines(): if not line.startswith(' '): comps = line.split(':') if_ = comps[1].strip() opts_comp...
Parse the contents of/ proc/ net/ route
def _parse_routes(): ''' Parse the contents of ``/proc/net/route`` ''' with salt.utils.files.fopen('/proc/net/route', 'r') as fp_: out = salt.utils.stringutils.to_unicode(fp_.read()) ret = {} for line in out.splitlines(): tmp = {} if not line.strip(): continu...
Convert hex fields from/ proc/ net/ route to octects
def _hex_to_octets(addr): ''' Convert hex fields from /proc/net/route to octects ''' return '{0}:{1}:{2}:{3}'.format( int(addr[6:8], 16), int(addr[4:6], 16), int(addr[2:4], 16), int(addr[0:2], 16), )
https:// github. com/ torvalds/ linux/ blob/ master/ include/ uapi/ linux/ route. h https:// github. com/ torvalds/ linux/ blob/ master/ include/ uapi/ linux/ ipv6_route. h
def _route_flags(rflags): ''' https://github.com/torvalds/linux/blob/master/include/uapi/linux/route.h https://github.com/torvalds/linux/blob/master/include/uapi/linux/ipv6_route.h ''' flags = '' fmap = { 0x0001: 'U', # RTF_UP, route is up 0x0002: 'G', # RTF_GATEWAY, use gatewa...
Returns the state of connman
def _get_state(): ''' Returns the state of connman ''' try: return pyconnman.ConnManager().get_property('State') except KeyError: return 'offline' except dbus.DBusException as exc: raise salt.exceptions.CommandExecutionError('Connman daemon error: {0}'.format(exc))
Returns the technologies of connman
def _get_technologies(): ''' Returns the technologies of connman ''' tech = '' technologies = pyconnman.ConnManager().get_technologies() for path, params in technologies: tech += '{0}\n\tName = {1}\n\tType = {2}\n\tPowered = {3}\n\tConnected = {4}\n'.format( path, params['Nam...
Returns a list with all connman services
def _get_services(): ''' Returns a list with all connman services ''' serv = [] services = pyconnman.ConnManager().get_services() for path, _ in services: serv.append(six.text_type(path[len(SERVICE_PATH):])) return serv
Verify if a connman service is connected
def _connected(service): ''' Verify if a connman service is connected ''' state = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)).get_property('State') return state == 'online' or state == 'ready'
validate that a value contains one or more space - delimited values
def _space_delimited_list(value): ''' validate that a value contains one or more space-delimited values ''' if isinstance(value, six.string_types): items = value.split(' ') valid = items and all(items) else: valid = hasattr(value, '__iter__') and (value != []) if valid: ...
validate ipv4 values
def _validate_ipv4(value): ''' validate ipv4 values ''' if len(value) == 3: if not salt.utils.validate.net.ipv4_addr(value[0].strip()): return False, 'Invalid ip address: {0} for ipv4 option'.format(value[0]) if not salt.utils.validate.net.netmask(value[1].strip()): ...
returns the coresponding service to given interface if exists otherwise return None
def _interface_to_service(iface): ''' returns the coresponding service to given interface if exists, otherwise return None ''' for _service in _get_services(): service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, _service)) if service_info.get_property('Ethernet')['Interface']...
return details about given connman service
def _get_service_info(service): ''' return details about given connman service ''' service_info = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) data = { 'label': service, 'wireless': service_info.get_property('Type') == 'wifi', 'connectionid': six.text_type(servi...
return dns list
def _get_dns_info(): ''' return dns list ''' dns_list = [] try: with salt.utils.files.fopen('/etc/resolv.conf', 'r+') as dns_info: lines = dns_info.readlines() for line in lines: if 'nameserver' in line: dns = line.split()[1].strip(...
Get values for some options and a given section from a config file.
def _load_config(section, options, default_value='', filename=INI_FILE): ''' Get values for some options and a given section from a config file. :param section: Section Name :param options: List of options :param default_value: Default value if an option doesn't have a value. Default is empty strin...
return requestmode for given interface
def _get_request_mode_info(interface): ''' return requestmode for given interface ''' settings = _load_config(interface, ['linklocalenabled', 'dhcpenabled'], -1) link_local_enabled = int(settings['linklocalenabled']) dhcp_enabled = int(settings['dhcpenabled']) if dhcp_enabled == 1: ...
Return possible adapter modes for a given interface using a blacklist.
def _get_possible_adapter_modes(interface, blacklist): ''' Return possible adapter modes for a given interface using a blacklist. :param interface: interface name :param blacklist: given blacklist :return: list of possible adapter modes ''' adapter_modes = [] protocols = _load_config('l...
Return information about an interface from config file.
def _get_static_info(interface): ''' Return information about an interface from config file. :param interface: interface label ''' data = { 'connectionid': interface.name, 'label': interface.name, 'hwaddr': interface.hwaddr[:-1], 'up': False, 'ipv4': { ...
return base details about given interface
def _get_base_interface_info(interface): ''' return base details about given interface ''' blacklist = { 'tcpip': { 'name': [], 'type': [], 'additional_protocol': False }, 'disabled': { 'name': ['eth0'], 'type': ['gadget...
return details about given ethercat interface
def _get_ethercat_interface_info(interface): ''' return details about given ethercat interface ''' base_information = _get_base_interface_info(interface) base_information['ethercat'] = { 'masterid': _load_config(interface.name, ['MasterID'])['MasterID'] } return base_information
return details about given tcpip interface
def _get_tcpip_interface_info(interface): ''' return details about given tcpip interface ''' base_information = _get_base_interface_info(interface) if base_information['ipv4']['requestmode'] == 'static': settings = _load_config(interface.name, ['IP_Address', 'Subnet_Mask', 'Gateway', 'DNS_Ad...
return details about given interface
def _get_interface_info(interface): ''' return details about given interface ''' adapter_mode = _get_adapter_mode_info(interface.name) if adapter_mode == 'disabled': return _get_base_interface_info(interface) elif adapter_mode == 'ethercat': return _get_ethercat_interface_info(in...
converts a dictionary object into a list of strings
def _dict_to_string(dictionary): ''' converts a dictionary object into a list of strings ''' ret = '' for key, val in sorted(dictionary.items()): if isinstance(val, dict): for line in _dict_to_string(val): ret += six.text_type(key) + '-' + line + '\n' elif...
Get details about all the interfaces on the minion
def get_interfaces_details(): ''' Get details about all the interfaces on the minion :return: information about all interfaces omitting loopback :rtype: dictionary CLI Example: .. code-block:: bash salt '*' ip.get_interfaces_details ''' _interfaces = [interface for interface ...
Enable or disable an interface on a legacy distro
def _change_state_legacy(interface, new_state): ''' Enable or disable an interface on a legacy distro Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service w...
Enable or disable an interface
def _change_state(interface, new_state): ''' Enable or disable an interface Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param interface: interface label :param new_state: up or down :return: True if the service was enabled, otherwise an e...
Helper function to persist a configuration in the ini file
def _save_config(section, token, value): ''' Helper function to persist a configuration in the ini file ''' cmd = NIRTCFG_PATH cmd += ' --set section={0},token=\'{1}\',value=\'{2}\''.format(section, token, value) if __salt__['cmd.run_all'](cmd)['retcode'] != 0: exc_msg = 'Error: could no...
Configure specified adapter to use EtherCAT adapter mode. If successful the target will need reboot if it doesn t already use EtherCAT adapter mode otherwise will return true.
def set_ethercat(interface, master_id): ''' Configure specified adapter to use EtherCAT adapter mode. If successful, the target will need reboot if it doesn't already use EtherCAT adapter mode, otherwise will return true. :param interface: interface label :param master_id: EtherCAT Master ID :r...
Configure specified adapter to use DHCP with linklocal fallback
def set_dhcp_linklocal_all(interface): ''' Configure specified adapter to use DHCP with linklocal fallback Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise ...
Configure specified adapter to use DHCP only
def set_dhcp_only_all(interface): ''' Configure specified adapter to use DHCP only Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :return: True if the settings were applied, otherwise an exception will be thr...
Configure an interface that is not detected as a service by Connman ( i. e. link is down )
def _configure_static_interface(interface, **settings): ''' Configure an interface that is not detected as a service by Connman (i.e. link is down) :param interface: interface label :param settings: - ip - netmask - gateway - dns - name :r...
Configure specified adapter to use ipv4 manual settings
def set_static_all(interface, address, netmask, gateway, nameservers=None): ''' Configure specified adapter to use ipv4 manual settings Change adapter mode to TCP/IP. If previous adapter mode was EtherCAT, the target will need reboot. :param str interface: interface label :param str address: ipv4 ...
Returns details about given interface.
def get_interface(iface): ''' Returns details about given interface. CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' _interfaces = get_interfaces_details() for _interface in _interfaces['interfaces']: if _interface['connectionid'] == iface: ...
Build an interface script for a network interface.
def build_interface(iface, iface_type, enabled, **settings): ''' Build an interface script for a network interface. CLI Example: .. code-block:: bash salt '*' ip.build_interface eth0 eth <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandEx...
Build the global network script.
def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this versi...
Return the contents of the global network script.
def get_network_settings(): ''' Return the contents of the global network script. CLI Example: .. code-block:: bash salt '*' ip.get_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') ...
Apply global network configuration.
def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') ...
Return an event object suitable for the named transport
def get_event( node, sock_dir=None, transport='zeromq', opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False): ''' Return an event object suitable for the named transport :param IOLoop io_loop: Pass in an io_loop if you want asynchronous opera...
Return an event object suitable for the named transport
def get_master_event(opts, sock_dir, listen=True, io_loop=None, raise_errors=False, keep_loop=False): ''' Return an event object suitable for the named transport ''' # TODO: AIO core is separate from transport if opts['transport'] in ('zeromq', 'tcp', 'detect'): return MasterEvent(sock_dir, ...
Fire an event containing the arguments passed to an orchestration job
def fire_args(opts, jid, tag_data, prefix=''): ''' Fire an event containing the arguments passed to an orchestration job ''' try: tag_suffix = [jid, 'args'] except NameError: pass else: tag = tagify(tag_suffix, prefix) try: _event = get_master_event(op...
convenience function to build a namespaced event tag string from joining with the TABPART character the base prefix and suffix
def tagify(suffix='', prefix='', base=SALT): ''' convenience function to build a namespaced event tag string from joining with the TABPART character the base, prefix and suffix If string prefix is a valid key in TAGS Then use the value of key prefix Else use prefix string If suffix is a list T...
Calculate the master stats and return the updated stat info
def update_stats(stats, start_time, data): ''' Calculate the master stats and return the updated stat info ''' end_time = time.time() cmd = data['cmd'] # the jid is used as the create time try: jid = data['jid'] except KeyError: try: jid = data['data']['__pub_...
Return the string URI for the location of the pull and pub sockets to use for firing and listening to events
def __load_uri(self, sock_dir, node): ''' Return the string URI for the location of the pull and pub sockets to use for firing and listening to events ''' if node == 'master': if self.opts['ipc_mode'] == 'tcp': puburi = int(self.opts['tcp_master_pub_po...
Subscribe to events matching the passed tag.
def subscribe(self, tag=None, match_type=None): ''' Subscribe to events matching the passed tag. If you do not subscribe to a tag, events will be discarded by calls to get_event that request a different tag. In contexts where many different jobs are outstanding it is important t...
Un - subscribe to events matching the passed tag.
def unsubscribe(self, tag, match_type=None): ''' Un-subscribe to events matching the passed tag. ''' if tag is None: return match_func = self._get_match_func(match_type) self.pending_tags.remove([tag, match_func]) old_events = self.pending_events ...
Establish the publish connection
def connect_pub(self, timeout=None): ''' Establish the publish connection ''' if self.cpub: return True if self._run_io_loop_sync: with salt.utils.asynchronous.current_ioloop(self.io_loop): if self.subscriber is None: s...
Close the publish connection ( if established )
def close_pub(self): ''' Close the publish connection (if established) ''' if not self.cpub: return self.subscriber.close() self.subscriber = None self.pending_events = [] self.cpub = False
Establish a connection with the event pull socket Default timeout is 1 s
def connect_pull(self, timeout=1): ''' Establish a connection with the event pull socket Default timeout is 1 s ''' if self.cpush: return True if self._run_io_loop_sync: with salt.utils.asynchronous.current_ioloop(self.io_loop): if...
Check the pending_events list for events that match the tag
def _check_pending(self, tag, match_func=None): """Check the pending_events list for events that match the tag :param tag: The tag to search for :type tag: str :param tags_regex: List of re expressions to search for also :type tags_regex: list[re.compile()] :return: ...
Check if the event_tag matches the search check. Uses regular expression search to check. Return True ( matches ) or False ( no match )
def _match_tag_regex(self, event_tag, search_tag): ''' Check if the event_tag matches the search check. Uses regular expression search to check. Return True (matches) or False (no match) ''' return self.cache_regex.get(search_tag).search(event_tag) is not None
Get a single publication. If no publication is available then block for up to wait seconds. Return publication if it is available or None if no publication is available.
def get_event(self, wait=5, tag='', full=False, match_type=None, no_block=False, auto_reconnect=False): ''' Get a single publication. If no publication is available, then block for up to `...
Get the raw event without blocking or any other niceties
def get_event_noblock(self): ''' Get the raw event without blocking or any other niceties ''' assert self._run_io_loop_sync if not self.cpub: if not self.connect_pub(): return None raw = self.subscriber.read_sync(timeout=0) if raw is N...
Creates a generator that continuously listens for events
def iter_events(self, tag='', full=False, match_type=None, auto_reconnect=False): ''' Creates a generator that continuously listens for events ''' while True: data = self.get_event(tag=tag, full=full, match_type=match_type, auto_reconnect=aut...
Send a single event into the publisher with payload dict data and event identifier tag
def fire_event(self, data, tag, timeout=1000): ''' Send a single event into the publisher with payload dict "data" and event identifier "tag" The default is 1000 ms ''' if not six.text_type(tag): # no empty tags allowed raise ValueError('Empty tag.') ...
Send a single event to the master with the payload data and the event identifier tag.
def fire_master(self, data, tag, timeout=1000): '''' Send a single event to the master, with the payload "data" and the event identifier "tag". Default timeout is 1000ms ''' msg = { 'tag': tag, 'data': data, 'events': None, ...
Helper function for fire_ret_load
def _fire_ret_load_specific_fun(self, load, fun_index=0): ''' Helper function for fire_ret_load ''' if isinstance(load['fun'], list): # Multi-function job fun = load['fun'][fun_index] # 'retcode' was already validated to exist and be non-zero ...
Fire events based on information in the return load
def fire_ret_load(self, load): ''' Fire events based on information in the return load ''' if load.get('retcode') and load.get('fun'): if isinstance(load['fun'], list): # Multi-function job if isinstance(load['retcode'], list): ...
Invoke the event_handler callback each time an event arrives.
def set_event_handler(self, event_handler): ''' Invoke the event_handler callback each time an event arrives. ''' assert not self._run_io_loop_sync if not self.cpub: self.connect_pub() self.subscriber.callbacks.add(event_handler) if not self.subscrib...