Search is not available for this dataset
text stringlengths 75 104k |
|---|
def vb_list_machines(**kwargs):
'''
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: [{}]
'''
manager = vb_get_manager()
mac... |
def vb_create_machine(name=None):
'''
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
'''
vbox = vb_get_box()
log.info('Create virtualbox m... |
def vb_clone_vm(
name=None,
clone_from=None,
clone_mode=0,
timeout=10000,
**kwargs
):
'''
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 tim... |
def _start_machine(machine, session):
'''
Helper to try and start machines
@param machine:
@type machine: IMachine
@param session:
@type session: ISession
@return:
@rtype: IProgress or None
'''
try:
return machine.launchVMProcess(session, '', '')
except Exception as ... |
def vb_start_vm(name=None, timeout=10000, **kwargs):
'''
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_stop_vm(name=None, timeout=10000, **kwargs):
'''
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_destroy_machine(name=None, timeout=10000):
'''
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
'''
vbox = vb_get_box()
log.info('Destroying machine %s', name)
machine = vbox.findMach... |
def vb_xpcom_to_attribute_dict(xpcom,
interface_name=None,
attributes=None,
excluded_attributes=None,
extra_attributes=None
):
'''
Attempts to build a dict f... |
def treat_machine_dict(machine):
'''
Make machine presentable for outside world.
!!!Modifies the input machine!!!
@param machine:
@type machine: dict
@return: the modified input machine
@rtype: dict
'''
machine.update({
'id': machine.get('id', ''),
'image': machine.... |
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:
'''
try:
vbox = vb_get_box()
vbox.findMachine(name)
return True
except Exception as e:
if isinst... |
def vb_get_machine(name, **kwargs):
'''
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
'''
vbox = vb_get_bo... |
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 = {}
for key in set((new or {})).union((old or {})):
if key not in old:
# New key
ret[key] = {'... |
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()
for item in new:
if item not in old:
ret['new'] = item
for item in old:
if item not in ... |
def decode(data, encoding=None, errors='strict', keep=False,
normalize=False, preserve_dict_class=False, preserve_tuples=False,
to_str=False):
'''
Generic function which will decode whichever type is passed, if necessary.
Optionally use to_str=True to ensure strings are str types and n... |
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. Optionally use to_str=True to ensure
strings are str types and not unicode on Python 2.
'''
return tuple(
de... |
def encode(data, encoding=None, errors='strict', keep=False,
preserve_dict_class=False, preserve_tuples=False):
'''
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. ... |
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):
if isinstance(key, tuple)... |
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_list(item, encoding, errors, keep,
... |
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)) |
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
# Default value would be an empty list if lookup not found
... |
def traverse_dict(data, key, default=None, delimiter=DEFAULT_TARGET_DELIM):
'''
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
... |
def traverse_dict_and_list(data, key, default=None, delimiter=DEFAULT_TARGET_DELIM):
'''
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
... |
def subdict_match(data,
expr,
delimiter=DEFAULT_TARGET_DELIM,
regex_match=False,
exact_match=False):
'''
Check for a match in a dictionary using a delimiter character to denote
levels of subdicts, and also allowing the delimiter charact... |
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 in data:
if isinstance(element, dict):
if len(element) != 1:
retur... |
def repack_dictlist(data,
strict=False,
recurse=False,
key_cb=None,
val_cb=None):
'''
Takes a list of one-element dicts (as found in many SLS schemas) and
repacks into a single dictionary.
'''
if isinstance(data, six.str... |
def is_iter(y, ignore=six.string_types):
'''
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 i... |
def is_true(value=None):
'''
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
'''
# Fir... |
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 = line.split('|')
for comp in range(len(comps)):... |
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_types, six.text_type, six.integer_types, float, bool)
simpletypes_values = tuple(list(simplety... |
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 isinstance(item, str):
item = salt.utils.stringutils.to_unicode(item)
elif not isinstance(ite... |
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 jmespath.search(expr, data) |
def _is_not_considered_falsey(value, ignore_types=()):
'''
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
'''
retu... |
def filter_falsey(data, recurse_depth=None, ignore_types=()):
'''
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: Sou... |
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)) |
def write(name, domain, value, vtype='string', user=None):
'''
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,... |
def absent(name, domain, user=None):
'''
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
'''
ret = {'name': name,
'result': True,
... |
def info(name):
'''
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
'''
info = __salt__['user.info'](name... |
def get_class_paths(_class, saltclass_path):
'''
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... |
def get_class_from_file(_file, 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: Absolu... |
def match_class_glob(_class, saltclass_path):
'''
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/salt... |
def expand_classes_glob(classes, salt_data):
'''
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)
'''
all... |
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 isinstance(value, float) or isinstance(value, bool) |
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
else:
type_ = next(six.iterkeys(configuration))
... |
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 |
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)
_current_parameter_value.add_argument(arg)... |
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 value != '':
_current_parameter_value = SimpleP... |
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_parameter(_current_parameter)
else:
# must be a... |
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_
_create_and_add_parameters(params)
_current_statemen... |
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) |
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' |
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) |
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) |
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_)
_parse_statement(options)
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)
channel = UnnamedStatement(type='chann... |
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_definition(i, _current_... |
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
_INDENT = ''
if type_ == 'config':
_current_statement = Gi... |
def config(name,
config,
write=True):
'''
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
... |
def set_binary_path(name):
'''
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.se... |
def set_config_file(name):
'''
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
'''
global __SYSLOG_NG_CONFIG_FILE
old = __SYSLOG_NG_CONFIG_FILE
__SYSL... |
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)
return __salt__['cmd.run_all'](params, env=env, python_shell=False) |
def set_parameters(version=None,
binary_path=None,
config_file=None,
*args,
**kwargs):
'''
Sets variables.
CLI Example:
.. code-block:: bash
salt '*' syslog_ng.set_parameters version='3.6'
salt '*' syslog_ng.s... |
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:
# Custom environment variables should be str types. This code
... |
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:
ret['stdout'] = stdout
if stderr is not None:
ret['stderr'] = stderr
r... |
def version(syslog_ng_sbin_dir=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.... |
def modules(syslog_ng_sbin_dir=None):
'''
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/in... |
def stats(syslog_ng_sbin_dir=None):
'''
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 '*' sy... |
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} |
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)) |
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)) |
def stop(name=None):
'''
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
... |
def start(name=None,
user=None,
group=None,
chroot=None,
caps=None,
no_caps=False,
pidfile=None,
enable_core=False,
fd_limit=None,
verbose=False,
debug=False,
trace=False,
yydebug=False,
per... |
def reload_(name):
'''
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 '*' syslo... |
def write_config(config, newlines=2):
'''
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.
CL... |
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 = config[key]
try:
with salt.utils.files.fopen(... |
def write_version(name):
'''
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... |
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.iterable) >= 1:
body = self.join_body_on.... |
def build(self):
'''
Builds the textual representation of the whole configuration object
with it's children.
'''
header = self.build_header()
body = self.build_body()
tail = self.build_tail()
return header + body + tail |
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, 'org.freedesktop.DBus.Properties')
system_lo... |
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.run']('localectl status') or '').strip()
ctl_key =... |
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.
'''
locale_params = _parse_dbus_locale() if dbus is not None else _localectl_status().get('system_locale', {})
locale_params['LANG']... |
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__)
# localectl on SLE12 is installed but the integration is still broken in latest SP3 due to
# config... |
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.systemd.booted(__context__)
# localectl on SLE12 is installed but the integration is broken -- config is rewritten by YaST2... |
def avail(locale):
'''
Check if a locale is available.
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' locale.avail 'en_US.UTF-8'
'''
try:
normalized_locale = salt.utils.locales.normalize_locale(locale)
except IndexError:
log.error('Unabl... |
def gen_locale(locale, **kwargs):
'''
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 loca... |
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 exc:
rai... |
def deployed(name, template=None, environment=None, params=None, poll=5,
rollback=False, timeout=60, update=False, profile=None,
**connection_args):
'''
Deploy stack with the specified properties
name
The name of the stack
template
File of template
enviro... |
def absent(name, poll=5, timeout=60, profile=None):
'''
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 _username():
'''
Grain for the minion username
'''
if pwd:
username = pwd.getpwuid(os.getuid()).pw_name
else:
username = getpass.getuser()
return username |
def _groupname():
'''
Grain for the minion groupname
'''
if grp:
try:
groupname = grp.getgrgid(os.getgid()).gr_name
except KeyError:
groupname = ''
else:
groupname = ''
return groupname |
def unpackage(package_):
'''
Unpackages a payload
'''
return salt.utils.msgpack.loads(package_, use_list=True,
_msgpack_module=msgpack) |
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 the load dict.
'''
payload = {'enc': enc}
load = {}
for key in kwargs:
load[key] = kwargs[key]
payload['load'] = load... |
def loads(self, msg, encoding=None, raw=False):
'''
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' t... |
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:
return self.loads(data) |
def dumps(self, msg, use_bin_type=False):
'''
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.
... |
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 the 'bytes' and 'str' types are distinguishable
... |
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(
zmq.R... |
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:
log.trace('Unregistering s... |
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.socket.send(pkg)
self.poller.register(self.socket, zmq... |
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) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.