repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/utils/virtualbox.py | vb_list_machines | 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()
machines = manager.getArray(vb_get_box(), 'machines')
return [
vb_xpcom_to_attribute_dict(machine, 'IMachine', **kwargs)
for machine in machines
] | python | 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()
machines = manager.getArray(vb_get_box(), 'machines')
return [
vb_xpcom_to_attribute_dict(machine, 'IMachine', **kwargs)
for machine in machines
] | [
"def",
"vb_list_machines",
"(",
"*",
"*",
"kwargs",
")",
":",
"manager",
"=",
"vb_get_manager",
"(",
")",
"machines",
"=",
"manager",
".",
"getArray",
"(",
"vb_get_box",
"(",
")",
",",
"'machines'",
")",
"return",
"[",
"vb_xpcom_to_attribute_dict",
"(",
"mac... | 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: [{}] | [
"Which",
"machines",
"does",
"the",
"hypervisor",
"have"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/virtualbox.py#L329-L342 | train |
saltstack/salt | salt/utils/virtualbox.py | vb_create_machine | 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 machine %s ', name)
groups = None
os_type_id = 'Other'
new_machine = vbox.createMachine(
None, # Settings file
name,
groups,
os_type_id,
None # flags
)
vbox.registerMachine(new_machine)
log.info('Finished creating %s', name)
return vb_xpcom_to_attribute_dict(new_machine, 'IMachine') | python | 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 machine %s ', name)
groups = None
os_type_id = 'Other'
new_machine = vbox.createMachine(
None, # Settings file
name,
groups,
os_type_id,
None # flags
)
vbox.registerMachine(new_machine)
log.info('Finished creating %s', name)
return vb_xpcom_to_attribute_dict(new_machine, 'IMachine') | [
"def",
"vb_create_machine",
"(",
"name",
"=",
"None",
")",
":",
"vbox",
"=",
"vb_get_box",
"(",
")",
"log",
".",
"info",
"(",
"'Create virtualbox machine %s '",
",",
"name",
")",
"groups",
"=",
"None",
"os_type_id",
"=",
"'Other'",
"new_machine",
"=",
"vbox"... | 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 | [
"Creates",
"a",
"machine",
"on",
"the",
"virtualbox",
"hypervisor"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/virtualbox.py#L345-L368 | train |
saltstack/salt | salt/utils/virtualbox.py | vb_clone_vm | 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 time in milliseconds to wait or -1 to wait indefinitely
@type timeout: int
@return dict of resulting VM
'''
vbox = vb_get_box()
log.info('Clone virtualbox machine %s from %s', name, clone_from)
source_machine = vbox.findMachine(clone_from)
groups = None
os_type_id = 'Other'
new_machine = vbox.createMachine(
None, # Settings file
name,
groups,
os_type_id,
None # flags
)
progress = source_machine.cloneTo(
new_machine,
clone_mode, # CloneMode
None # CloneOptions : None = Full?
)
progress.waitForCompletion(timeout)
log.info('Finished cloning %s from %s', name, clone_from)
vbox.registerMachine(new_machine)
return vb_xpcom_to_attribute_dict(new_machine, 'IMachine') | python | 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 time in milliseconds to wait or -1 to wait indefinitely
@type timeout: int
@return dict of resulting VM
'''
vbox = vb_get_box()
log.info('Clone virtualbox machine %s from %s', name, clone_from)
source_machine = vbox.findMachine(clone_from)
groups = None
os_type_id = 'Other'
new_machine = vbox.createMachine(
None, # Settings file
name,
groups,
os_type_id,
None # flags
)
progress = source_machine.cloneTo(
new_machine,
clone_mode, # CloneMode
None # CloneOptions : None = Full?
)
progress.waitForCompletion(timeout)
log.info('Finished cloning %s from %s', name, clone_from)
vbox.registerMachine(new_machine)
return vb_xpcom_to_attribute_dict(new_machine, 'IMachine') | [
"def",
"vb_clone_vm",
"(",
"name",
"=",
"None",
",",
"clone_from",
"=",
"None",
",",
"clone_mode",
"=",
"0",
",",
"timeout",
"=",
"10000",
",",
"*",
"*",
"kwargs",
")",
":",
"vbox",
"=",
"vb_get_box",
"(",
")",
"log",
".",
"info",
"(",
"'Clone virtua... | 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 | [
"Tells",
"virtualbox",
"to",
"create",
"a",
"VM",
"by",
"cloning",
"from",
"an",
"existing",
"one"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/virtualbox.py#L371-L415 | train |
saltstack/salt | salt/utils/virtualbox.py | _start_machine | 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 e:
log.debug(e.message, exc_info=True)
return None | python | 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 e:
log.debug(e.message, exc_info=True)
return None | [
"def",
"_start_machine",
"(",
"machine",
",",
"session",
")",
":",
"try",
":",
"return",
"machine",
".",
"launchVMProcess",
"(",
"session",
",",
"''",
",",
"''",
")",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"debug",
"(",
"e",
".",
"message",... | Helper to try and start machines
@param machine:
@type machine: IMachine
@param session:
@type session: ISession
@return:
@rtype: IProgress or None | [
"Helper",
"to",
"try",
"and",
"start",
"machines"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/virtualbox.py#L418-L433 | train |
saltstack/salt | salt/utils/virtualbox.py | vb_start_vm | 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
'''
# Time tracking
start_time = time.time()
timeout_in_seconds = timeout / 1000
max_time = start_time + timeout_in_seconds
vbox = vb_get_box()
machine = vbox.findMachine(name)
session = _virtualboxManager.getSessionObject(vbox)
log.info('Starting machine %s in state %s', name, vb_machinestate_to_str(machine.state))
try:
# Keep trying to start a machine
args = (machine, session)
progress = wait_for(_start_machine, timeout=timeout_in_seconds, func_args=args)
if not progress:
progress = machine.launchVMProcess(session, '', '')
# We already waited for stuff, don't push it
time_left = max_time - time.time()
progress.waitForCompletion(time_left * 1000)
finally:
_virtualboxManager.closeMachineSession(session)
# The session state should best be unlocked otherwise subsequent calls might cause problems
time_left = max_time - time.time()
vb_wait_for_session_state(session, timeout=time_left)
log.info('Started machine %s', name)
return vb_xpcom_to_attribute_dict(machine, 'IMachine') | python | 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
'''
# Time tracking
start_time = time.time()
timeout_in_seconds = timeout / 1000
max_time = start_time + timeout_in_seconds
vbox = vb_get_box()
machine = vbox.findMachine(name)
session = _virtualboxManager.getSessionObject(vbox)
log.info('Starting machine %s in state %s', name, vb_machinestate_to_str(machine.state))
try:
# Keep trying to start a machine
args = (machine, session)
progress = wait_for(_start_machine, timeout=timeout_in_seconds, func_args=args)
if not progress:
progress = machine.launchVMProcess(session, '', '')
# We already waited for stuff, don't push it
time_left = max_time - time.time()
progress.waitForCompletion(time_left * 1000)
finally:
_virtualboxManager.closeMachineSession(session)
# The session state should best be unlocked otherwise subsequent calls might cause problems
time_left = max_time - time.time()
vb_wait_for_session_state(session, timeout=time_left)
log.info('Started machine %s', name)
return vb_xpcom_to_attribute_dict(machine, 'IMachine') | [
"def",
"vb_start_vm",
"(",
"name",
"=",
"None",
",",
"timeout",
"=",
"10000",
",",
"*",
"*",
"kwargs",
")",
":",
"# Time tracking",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"timeout_in_seconds",
"=",
"timeout",
"/",
"1000",
"max_time",
"=",
"sta... | 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 | [
"Tells",
"Virtualbox",
"to",
"start",
"up",
"a",
"VM",
".",
"Blocking",
"function!"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/virtualbox.py#L436-L475 | train |
saltstack/salt | salt/utils/virtualbox.py | vb_stop_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
'''
vbox = vb_get_box()
machine = vbox.findMachine(name)
log.info('Stopping machine %s', name)
session = _virtualboxManager.openMachineSession(machine)
try:
console = session.console
progress = console.powerDown()
progress.waitForCompletion(timeout)
finally:
_virtualboxManager.closeMachineSession(session)
vb_wait_for_session_state(session)
log.info('Stopped machine %s is now %s', name, vb_machinestate_to_str(machine.state))
return vb_xpcom_to_attribute_dict(machine, 'IMachine') | python | 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
'''
vbox = vb_get_box()
machine = vbox.findMachine(name)
log.info('Stopping machine %s', name)
session = _virtualboxManager.openMachineSession(machine)
try:
console = session.console
progress = console.powerDown()
progress.waitForCompletion(timeout)
finally:
_virtualboxManager.closeMachineSession(session)
vb_wait_for_session_state(session)
log.info('Stopped machine %s is now %s', name, vb_machinestate_to_str(machine.state))
return vb_xpcom_to_attribute_dict(machine, 'IMachine') | [
"def",
"vb_stop_vm",
"(",
"name",
"=",
"None",
",",
"timeout",
"=",
"10000",
",",
"*",
"*",
"kwargs",
")",
":",
"vbox",
"=",
"vb_get_box",
"(",
")",
"machine",
"=",
"vbox",
".",
"findMachine",
"(",
"name",
")",
"log",
".",
"info",
"(",
"'Stopping mac... | 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 | [
"Tells",
"Virtualbox",
"to",
"stop",
"a",
"VM",
".",
"This",
"is",
"a",
"blocking",
"function!"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/virtualbox.py#L478-L501 | train |
saltstack/salt | salt/utils/virtualbox.py | vb_destroy_machine | 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.findMachine(name)
files = machine.unregister(2)
progress = machine.deleteConfig(files)
progress.waitForCompletion(timeout)
log.info('Finished destroying machine %s', name) | python | 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.findMachine(name)
files = machine.unregister(2)
progress = machine.deleteConfig(files)
progress.waitForCompletion(timeout)
log.info('Finished destroying machine %s', name) | [
"def",
"vb_destroy_machine",
"(",
"name",
"=",
"None",
",",
"timeout",
"=",
"10000",
")",
":",
"vbox",
"=",
"vb_get_box",
"(",
")",
"log",
".",
"info",
"(",
"'Destroying machine %s'",
",",
"name",
")",
"machine",
"=",
"vbox",
".",
"findMachine",
"(",
"na... | 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 | [
"Attempts",
"to",
"get",
"rid",
"of",
"a",
"machine",
"and",
"all",
"its",
"files",
"from",
"the",
"hypervisor"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/virtualbox.py#L504-L517 | train |
saltstack/salt | salt/utils/virtualbox.py | vb_xpcom_to_attribute_dict | def vb_xpcom_to_attribute_dict(xpcom,
interface_name=None,
attributes=None,
excluded_attributes=None,
extra_attributes=None
):
'''
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 interface we will be converting from.
Without this it's best to specify the list of attributes you want
@type interface_name: str
@param attributes: Overrides the attributes used from XPCOM_ATTRIBUTES
@type attributes: attribute_list
@param excluded_attributes: Which should be excluded in the returned dict.
!!These take precedence over extra_attributes!!
@type excluded_attributes: attribute_list
@param extra_attributes: Which should be retrieved in addition those already being retrieved
@type extra_attributes: attribute_list
@return:
@rtype: dict
'''
# Check the interface
if interface_name:
m = re.search(r'XPCOM.+implementing {0}'.format(interface_name), six.text_type(xpcom))
if not m:
# TODO maybe raise error here?
log.warning('Interface %s is unknown and cannot be converted to dict', interface_name)
return dict()
interface_attributes = set(attributes or XPCOM_ATTRIBUTES.get(interface_name, []))
if extra_attributes:
interface_attributes = interface_attributes.union(extra_attributes)
if excluded_attributes:
interface_attributes = interface_attributes.difference(excluded_attributes)
attribute_tuples = []
for attribute in interface_attributes:
if isinstance(attribute, tuple):
attribute_name = attribute[0]
attribute_class = attribute[1]
value = (attribute_name, getattr(xpcom, attribute_name, attribute_class()))
else:
value = (attribute, getattr(xpcom, attribute, ''))
attribute_tuples.append(value)
return dict(attribute_tuples) | python | def vb_xpcom_to_attribute_dict(xpcom,
interface_name=None,
attributes=None,
excluded_attributes=None,
extra_attributes=None
):
'''
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 interface we will be converting from.
Without this it's best to specify the list of attributes you want
@type interface_name: str
@param attributes: Overrides the attributes used from XPCOM_ATTRIBUTES
@type attributes: attribute_list
@param excluded_attributes: Which should be excluded in the returned dict.
!!These take precedence over extra_attributes!!
@type excluded_attributes: attribute_list
@param extra_attributes: Which should be retrieved in addition those already being retrieved
@type extra_attributes: attribute_list
@return:
@rtype: dict
'''
# Check the interface
if interface_name:
m = re.search(r'XPCOM.+implementing {0}'.format(interface_name), six.text_type(xpcom))
if not m:
# TODO maybe raise error here?
log.warning('Interface %s is unknown and cannot be converted to dict', interface_name)
return dict()
interface_attributes = set(attributes or XPCOM_ATTRIBUTES.get(interface_name, []))
if extra_attributes:
interface_attributes = interface_attributes.union(extra_attributes)
if excluded_attributes:
interface_attributes = interface_attributes.difference(excluded_attributes)
attribute_tuples = []
for attribute in interface_attributes:
if isinstance(attribute, tuple):
attribute_name = attribute[0]
attribute_class = attribute[1]
value = (attribute_name, getattr(xpcom, attribute_name, attribute_class()))
else:
value = (attribute, getattr(xpcom, attribute, ''))
attribute_tuples.append(value)
return dict(attribute_tuples) | [
"def",
"vb_xpcom_to_attribute_dict",
"(",
"xpcom",
",",
"interface_name",
"=",
"None",
",",
"attributes",
"=",
"None",
",",
"excluded_attributes",
"=",
"None",
",",
"extra_attributes",
"=",
"None",
")",
":",
"# Check the interface",
"if",
"interface_name",
":",
"m... | 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 interface we will be converting from.
Without this it's best to specify the list of attributes you want
@type interface_name: str
@param attributes: Overrides the attributes used from XPCOM_ATTRIBUTES
@type attributes: attribute_list
@param excluded_attributes: Which should be excluded in the returned dict.
!!These take precedence over extra_attributes!!
@type excluded_attributes: attribute_list
@param extra_attributes: Which should be retrieved in addition those already being retrieved
@type extra_attributes: attribute_list
@return:
@rtype: dict | [
"Attempts",
"to",
"build",
"a",
"dict",
"from",
"an",
"XPCOM",
"object",
".",
"Attributes",
"that",
"don",
"t",
"exist",
"in",
"the",
"object",
"return",
"an",
"empty",
"string",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/virtualbox.py#L520-L573 | train |
saltstack/salt | salt/utils/virtualbox.py | treat_machine_dict | 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.get('image', ''),
'size': '{0} MB'.format(machine.get('memorySize', 0)),
'state': machine_get_machinestate_str(machine),
'private_ips': [],
'public_ips': [],
})
# Replaced keys
if 'memorySize' in machine:
del machine['memorySize']
return machine | python | 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.get('image', ''),
'size': '{0} MB'.format(machine.get('memorySize', 0)),
'state': machine_get_machinestate_str(machine),
'private_ips': [],
'public_ips': [],
})
# Replaced keys
if 'memorySize' in machine:
del machine['memorySize']
return machine | [
"def",
"treat_machine_dict",
"(",
"machine",
")",
":",
"machine",
".",
"update",
"(",
"{",
"'id'",
":",
"machine",
".",
"get",
"(",
"'id'",
",",
"''",
")",
",",
"'image'",
":",
"machine",
".",
"get",
"(",
"'image'",
",",
"''",
")",
",",
"'size'",
"... | Make machine presentable for outside world.
!!!Modifies the input machine!!!
@param machine:
@type machine: dict
@return: the modified input machine
@rtype: dict | [
"Make",
"machine",
"presentable",
"for",
"outside",
"world",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/virtualbox.py#L576-L599 | train |
saltstack/salt | salt/utils/virtualbox.py | vb_machine_exists | 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 isinstance(e.message, six.string_types):
message = e.message
elif hasattr(e, 'msg') and isinstance(getattr(e, 'msg'), six.string_types):
message = getattr(e, 'msg')
else:
message = ''
if 0 > message.find('Could not find a registered machine named'):
log.error(message)
return False | python | 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 isinstance(e.message, six.string_types):
message = e.message
elif hasattr(e, 'msg') and isinstance(getattr(e, 'msg'), six.string_types):
message = getattr(e, 'msg')
else:
message = ''
if 0 > message.find('Could not find a registered machine named'):
log.error(message)
return False | [
"def",
"vb_machine_exists",
"(",
"name",
")",
":",
"try",
":",
"vbox",
"=",
"vb_get_box",
"(",
")",
"vbox",
".",
"findMachine",
"(",
"name",
")",
"return",
"True",
"except",
"Exception",
"as",
"e",
":",
"if",
"isinstance",
"(",
"e",
".",
"message",
","... | Checks in with the hypervisor to see if the machine with the given name is known
@param name:
@type name:
@return:
@rtype: | [
"Checks",
"in",
"with",
"the",
"hypervisor",
"to",
"see",
"if",
"the",
"machine",
"with",
"the",
"given",
"name",
"is",
"known"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/virtualbox.py#L652-L674 | train |
saltstack/salt | salt/utils/virtualbox.py | vb_get_machine | 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_box()
machine = vbox.findMachine(name)
return vb_xpcom_to_attribute_dict(machine, 'IMachine', **kwargs) | python | 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_box()
machine = vbox.findMachine(name)
return vb_xpcom_to_attribute_dict(machine, 'IMachine', **kwargs) | [
"def",
"vb_get_machine",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"vbox",
"=",
"vb_get_box",
"(",
")",
"machine",
"=",
"vbox",
".",
"findMachine",
"(",
"name",
")",
"return",
"vb_xpcom_to_attribute_dict",
"(",
"machine",
",",
"'IMachine'",
",",
"*",... | 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 | [
"Attempts",
"to",
"fetch",
"a",
"machine",
"from",
"Virtualbox",
"and",
"convert",
"it",
"to",
"a",
"dict"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/virtualbox.py#L677-L690 | train |
saltstack/salt | salt/utils/data.py | compare_dicts | 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] = {'old': '',
'new': new[key]}
elif key not in new:
# Key removed
ret[key] = {'new': '',
'old': old[key]}
elif new[key] != old[key]:
# Key modified
ret[key] = {'old': old[key],
'new': new[key]}
return ret | python | 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] = {'old': '',
'new': new[key]}
elif key not in new:
# Key removed
ret[key] = {'new': '',
'old': old[key]}
elif new[key] != old[key]:
# Key modified
ret[key] = {'old': old[key],
'new': new[key]}
return ret | [
"def",
"compare_dicts",
"(",
"old",
"=",
"None",
",",
"new",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"key",
"in",
"set",
"(",
"(",
"new",
"or",
"{",
"}",
")",
")",
".",
"union",
"(",
"(",
"old",
"or",
"{",
"}",
")",
")",
":",
... | Compare before and after results from various salt functions, returning a
dict describing the changes that were made. | [
"Compare",
"before",
"and",
"after",
"results",
"from",
"various",
"salt",
"functions",
"returning",
"a",
"dict",
"describing",
"the",
"changes",
"that",
"were",
"made",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/data.py#L124-L143 | train |
saltstack/salt | salt/utils/data.py | compare_lists | 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 new:
ret['old'] = item
return ret | python | 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 new:
ret['old'] = item
return ret | [
"def",
"compare_lists",
"(",
"old",
"=",
"None",
",",
"new",
"=",
"None",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"for",
"item",
"in",
"new",
":",
"if",
"item",
"not",
"in",
"old",
":",
"ret",
"[",
"'new'",
"]",
"=",
"item",
"for",
"item",
"in"... | Compare before and after results from various salt functions, returning a
dict describing the changes that were made | [
"Compare",
"before",
"and",
"after",
"results",
"from",
"various",
"salt",
"functions",
"returning",
"a",
"dict",
"describing",
"the",
"changes",
"that",
"were",
"made"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/data.py#L147-L159 | train |
saltstack/salt | salt/utils/data.py | decode | 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 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
original value to silently be returned in cases where decoding fails. This
can be useful for cases where the data passed to this function is likely to
contain binary blobs, such as in the case of cp.recv.
If `normalize` is True, then unicodedata.normalize() will be used to
normalize unicode strings down to a single code point per glyph. It is
recommended not to normalize unless you know what you're doing. For
instance, if `data` contains a dictionary, it is possible that normalizing
will lead to data loss because the following two strings will normalize to
the same value:
- u'\\u044f\\u0438\\u0306\\u0446\\u0430.txt'
- u'\\u044f\\u0439\\u0446\\u0430.txt'
One good use case for normalization is in the test suite. For example, on
some platforms such as Mac OS, os.listdir() will produce the first of the
two strings above, in which "й" is represented as two code points (i.e. one
for the base character, and one for the breve mark). Normalizing allows for
a more reliable test case.
'''
_decode_func = salt.utils.stringutils.to_unicode \
if not to_str \
else salt.utils.stringutils.to_str
if isinstance(data, Mapping):
return decode_dict(data, encoding, errors, keep, normalize,
preserve_dict_class, preserve_tuples, to_str)
elif isinstance(data, list):
return decode_list(data, encoding, errors, keep, normalize,
preserve_dict_class, preserve_tuples, to_str)
elif isinstance(data, tuple):
return decode_tuple(data, encoding, errors, keep, normalize,
preserve_dict_class, to_str) \
if preserve_tuples \
else decode_list(data, encoding, errors, keep, normalize,
preserve_dict_class, preserve_tuples, to_str)
else:
try:
data = _decode_func(data, encoding, errors, normalize)
except TypeError:
# to_unicode raises a TypeError when input is not a
# string/bytestring/bytearray. This is expected and simply means we
# are going to leave the value as-is.
pass
except UnicodeDecodeError:
if not keep:
raise
return data | python | 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 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
original value to silently be returned in cases where decoding fails. This
can be useful for cases where the data passed to this function is likely to
contain binary blobs, such as in the case of cp.recv.
If `normalize` is True, then unicodedata.normalize() will be used to
normalize unicode strings down to a single code point per glyph. It is
recommended not to normalize unless you know what you're doing. For
instance, if `data` contains a dictionary, it is possible that normalizing
will lead to data loss because the following two strings will normalize to
the same value:
- u'\\u044f\\u0438\\u0306\\u0446\\u0430.txt'
- u'\\u044f\\u0439\\u0446\\u0430.txt'
One good use case for normalization is in the test suite. For example, on
some platforms such as Mac OS, os.listdir() will produce the first of the
two strings above, in which "й" is represented as two code points (i.e. one
for the base character, and one for the breve mark). Normalizing allows for
a more reliable test case.
'''
_decode_func = salt.utils.stringutils.to_unicode \
if not to_str \
else salt.utils.stringutils.to_str
if isinstance(data, Mapping):
return decode_dict(data, encoding, errors, keep, normalize,
preserve_dict_class, preserve_tuples, to_str)
elif isinstance(data, list):
return decode_list(data, encoding, errors, keep, normalize,
preserve_dict_class, preserve_tuples, to_str)
elif isinstance(data, tuple):
return decode_tuple(data, encoding, errors, keep, normalize,
preserve_dict_class, to_str) \
if preserve_tuples \
else decode_list(data, encoding, errors, keep, normalize,
preserve_dict_class, preserve_tuples, to_str)
else:
try:
data = _decode_func(data, encoding, errors, normalize)
except TypeError:
# to_unicode raises a TypeError when input is not a
# string/bytestring/bytearray. This is expected and simply means we
# are going to leave the value as-is.
pass
except UnicodeDecodeError:
if not keep:
raise
return data | [
"def",
"decode",
"(",
"data",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
",",
"keep",
"=",
"False",
",",
"normalize",
"=",
"False",
",",
"preserve_dict_class",
"=",
"False",
",",
"preserve_tuples",
"=",
"False",
",",
"to_str",
"=",
"Fa... | 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
original value to silently be returned in cases where decoding fails. This
can be useful for cases where the data passed to this function is likely to
contain binary blobs, such as in the case of cp.recv.
If `normalize` is True, then unicodedata.normalize() will be used to
normalize unicode strings down to a single code point per glyph. It is
recommended not to normalize unless you know what you're doing. For
instance, if `data` contains a dictionary, it is possible that normalizing
will lead to data loss because the following two strings will normalize to
the same value:
- u'\\u044f\\u0438\\u0306\\u0446\\u0430.txt'
- u'\\u044f\\u0439\\u0446\\u0430.txt'
One good use case for normalization is in the test suite. For example, on
some platforms such as Mac OS, os.listdir() will produce the first of the
two strings above, in which "й" is represented as two code points (i.e. one
for the base character, and one for the breve mark). Normalizing allows for
a more reliable test case. | [
"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",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/data.py#L162-L218 | train |
saltstack/salt | salt/utils/data.py | decode_dict | 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.
'''
_decode_func = salt.utils.stringutils.to_unicode \
if not to_str \
else salt.utils.stringutils.to_str
# Make sure we preserve OrderedDicts
rv = data.__class__() if preserve_dict_class else {}
for key, value in six.iteritems(data):
if isinstance(key, tuple):
key = decode_tuple(key, encoding, errors, keep, normalize,
preserve_dict_class, to_str) \
if preserve_tuples \
else decode_list(key, encoding, errors, keep, normalize,
preserve_dict_class, preserve_tuples, to_str)
else:
try:
key = _decode_func(key, encoding, errors, normalize)
except TypeError:
# to_unicode raises a TypeError when input is not a
# string/bytestring/bytearray. This is expected and simply
# means we are going to leave the value as-is.
pass
except UnicodeDecodeError:
if not keep:
raise
if isinstance(value, list):
value = decode_list(value, encoding, errors, keep, normalize,
preserve_dict_class, preserve_tuples, to_str)
elif isinstance(value, tuple):
value = decode_tuple(value, encoding, errors, keep, normalize,
preserve_dict_class, to_str) \
if preserve_tuples \
else decode_list(value, encoding, errors, keep, normalize,
preserve_dict_class, preserve_tuples, to_str)
elif isinstance(value, Mapping):
value = decode_dict(value, encoding, errors, keep, normalize,
preserve_dict_class, preserve_tuples, to_str)
else:
try:
value = _decode_func(value, encoding, errors, normalize)
except TypeError:
# to_unicode raises a TypeError when input is not a
# string/bytestring/bytearray. This is expected and simply
# means we are going to leave the value as-is.
pass
except UnicodeDecodeError:
if not keep:
raise
rv[key] = value
return rv | python | 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.
'''
_decode_func = salt.utils.stringutils.to_unicode \
if not to_str \
else salt.utils.stringutils.to_str
# Make sure we preserve OrderedDicts
rv = data.__class__() if preserve_dict_class else {}
for key, value in six.iteritems(data):
if isinstance(key, tuple):
key = decode_tuple(key, encoding, errors, keep, normalize,
preserve_dict_class, to_str) \
if preserve_tuples \
else decode_list(key, encoding, errors, keep, normalize,
preserve_dict_class, preserve_tuples, to_str)
else:
try:
key = _decode_func(key, encoding, errors, normalize)
except TypeError:
# to_unicode raises a TypeError when input is not a
# string/bytestring/bytearray. This is expected and simply
# means we are going to leave the value as-is.
pass
except UnicodeDecodeError:
if not keep:
raise
if isinstance(value, list):
value = decode_list(value, encoding, errors, keep, normalize,
preserve_dict_class, preserve_tuples, to_str)
elif isinstance(value, tuple):
value = decode_tuple(value, encoding, errors, keep, normalize,
preserve_dict_class, to_str) \
if preserve_tuples \
else decode_list(value, encoding, errors, keep, normalize,
preserve_dict_class, preserve_tuples, to_str)
elif isinstance(value, Mapping):
value = decode_dict(value, encoding, errors, keep, normalize,
preserve_dict_class, preserve_tuples, to_str)
else:
try:
value = _decode_func(value, encoding, errors, normalize)
except TypeError:
# to_unicode raises a TypeError when input is not a
# string/bytestring/bytearray. This is expected and simply
# means we are going to leave the value as-is.
pass
except UnicodeDecodeError:
if not keep:
raise
rv[key] = value
return rv | [
"def",
"decode_dict",
"(",
"data",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
",",
"keep",
"=",
"False",
",",
"normalize",
"=",
"False",
",",
"preserve_dict_class",
"=",
"False",
",",
"preserve_tuples",
"=",
"False",
",",
"to_str",
"=",
... | Decode all string values to Unicode. Optionally use to_str=True to ensure
strings are str types and not unicode on Python 2. | [
"Decode",
"all",
"string",
"values",
"to",
"Unicode",
".",
"Optionally",
"use",
"to_str",
"=",
"True",
"to",
"ensure",
"strings",
"are",
"str",
"types",
"and",
"not",
"unicode",
"on",
"Python",
"2",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/data.py#L221-L277 | train |
saltstack/salt | salt/utils/data.py | decode_tuple | 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(
decode_list(data, encoding, errors, keep, normalize,
preserve_dict_class, True, to_str)
) | python | 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(
decode_list(data, encoding, errors, keep, normalize,
preserve_dict_class, True, to_str)
) | [
"def",
"decode_tuple",
"(",
"data",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
",",
"keep",
"=",
"False",
",",
"normalize",
"=",
"False",
",",
"preserve_dict_class",
"=",
"False",
",",
"to_str",
"=",
"False",
")",
":",
"return",
"tuple... | Decode all string values to Unicode. Optionally use to_str=True to ensure
strings are str types and not unicode on Python 2. | [
"Decode",
"all",
"string",
"values",
"to",
"Unicode",
".",
"Optionally",
"use",
"to_str",
"=",
"True",
"to",
"ensure",
"strings",
"are",
"str",
"types",
"and",
"not",
"unicode",
"on",
"Python",
"2",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/data.py#L320-L329 | train |
saltstack/salt | salt/utils/data.py | encode | 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. Passing `keep` as True allows for the
original value to silently be returned in cases where encoding fails. This
can be useful for cases where the data passed to this function is likely to
contain binary blobs.
'''
if isinstance(data, Mapping):
return encode_dict(data, encoding, errors, keep,
preserve_dict_class, preserve_tuples)
elif isinstance(data, list):
return encode_list(data, encoding, errors, keep,
preserve_dict_class, preserve_tuples)
elif isinstance(data, tuple):
return encode_tuple(data, encoding, errors, keep, preserve_dict_class) \
if preserve_tuples \
else encode_list(data, encoding, errors, keep,
preserve_dict_class, preserve_tuples)
else:
try:
return salt.utils.stringutils.to_bytes(data, encoding, errors)
except TypeError:
# to_bytes raises a TypeError when input is not a
# string/bytestring/bytearray. This is expected and simply
# means we are going to leave the value as-is.
pass
except UnicodeEncodeError:
if not keep:
raise
return data | python | 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. Passing `keep` as True allows for the
original value to silently be returned in cases where encoding fails. This
can be useful for cases where the data passed to this function is likely to
contain binary blobs.
'''
if isinstance(data, Mapping):
return encode_dict(data, encoding, errors, keep,
preserve_dict_class, preserve_tuples)
elif isinstance(data, list):
return encode_list(data, encoding, errors, keep,
preserve_dict_class, preserve_tuples)
elif isinstance(data, tuple):
return encode_tuple(data, encoding, errors, keep, preserve_dict_class) \
if preserve_tuples \
else encode_list(data, encoding, errors, keep,
preserve_dict_class, preserve_tuples)
else:
try:
return salt.utils.stringutils.to_bytes(data, encoding, errors)
except TypeError:
# to_bytes raises a TypeError when input is not a
# string/bytestring/bytearray. This is expected and simply
# means we are going to leave the value as-is.
pass
except UnicodeEncodeError:
if not keep:
raise
return data | [
"def",
"encode",
"(",
"data",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
",",
"keep",
"=",
"False",
",",
"preserve_dict_class",
"=",
"False",
",",
"preserve_tuples",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"Mappin... | 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 for cases where the data passed to this function is likely to
contain binary blobs. | [
"Generic",
"function",
"which",
"will",
"encode",
"whichever",
"type",
"is",
"passed",
"if",
"necessary"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/data.py#L332-L365 | train |
saltstack/salt | salt/utils/data.py | encode_dict | 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):
key = encode_tuple(key, encoding, errors, keep, preserve_dict_class) \
if preserve_tuples \
else encode_list(key, encoding, errors, keep,
preserve_dict_class, preserve_tuples)
else:
try:
key = salt.utils.stringutils.to_bytes(key, encoding, errors)
except TypeError:
# to_bytes raises a TypeError when input is not a
# string/bytestring/bytearray. This is expected and simply
# means we are going to leave the value as-is.
pass
except UnicodeEncodeError:
if not keep:
raise
if isinstance(value, list):
value = encode_list(value, encoding, errors, keep,
preserve_dict_class, preserve_tuples)
elif isinstance(value, tuple):
value = encode_tuple(value, encoding, errors, keep, preserve_dict_class) \
if preserve_tuples \
else encode_list(value, encoding, errors, keep,
preserve_dict_class, preserve_tuples)
elif isinstance(value, Mapping):
value = encode_dict(value, encoding, errors, keep,
preserve_dict_class, preserve_tuples)
else:
try:
value = salt.utils.stringutils.to_bytes(value, encoding, errors)
except TypeError:
# to_bytes raises a TypeError when input is not a
# string/bytestring/bytearray. This is expected and simply
# means we are going to leave the value as-is.
pass
except UnicodeEncodeError:
if not keep:
raise
rv[key] = value
return rv | python | 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):
key = encode_tuple(key, encoding, errors, keep, preserve_dict_class) \
if preserve_tuples \
else encode_list(key, encoding, errors, keep,
preserve_dict_class, preserve_tuples)
else:
try:
key = salt.utils.stringutils.to_bytes(key, encoding, errors)
except TypeError:
# to_bytes raises a TypeError when input is not a
# string/bytestring/bytearray. This is expected and simply
# means we are going to leave the value as-is.
pass
except UnicodeEncodeError:
if not keep:
raise
if isinstance(value, list):
value = encode_list(value, encoding, errors, keep,
preserve_dict_class, preserve_tuples)
elif isinstance(value, tuple):
value = encode_tuple(value, encoding, errors, keep, preserve_dict_class) \
if preserve_tuples \
else encode_list(value, encoding, errors, keep,
preserve_dict_class, preserve_tuples)
elif isinstance(value, Mapping):
value = encode_dict(value, encoding, errors, keep,
preserve_dict_class, preserve_tuples)
else:
try:
value = salt.utils.stringutils.to_bytes(value, encoding, errors)
except TypeError:
# to_bytes raises a TypeError when input is not a
# string/bytestring/bytearray. This is expected and simply
# means we are going to leave the value as-is.
pass
except UnicodeEncodeError:
if not keep:
raise
rv[key] = value
return rv | [
"def",
"encode_dict",
"(",
"data",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
",",
"keep",
"=",
"False",
",",
"preserve_dict_class",
"=",
"False",
",",
"preserve_tuples",
"=",
"False",
")",
":",
"rv",
"=",
"data",
".",
"__class__",
"("... | Encode all string values to bytes | [
"Encode",
"all",
"string",
"values",
"to",
"bytes"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/data.py#L370-L418 | train |
saltstack/salt | salt/utils/data.py | encode_list | 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,
preserve_dict_class, preserve_tuples)
elif isinstance(item, tuple):
item = encode_tuple(item, encoding, errors, keep, preserve_dict_class) \
if preserve_tuples \
else encode_list(item, encoding, errors, keep,
preserve_dict_class, preserve_tuples)
elif isinstance(item, Mapping):
item = encode_dict(item, encoding, errors, keep,
preserve_dict_class, preserve_tuples)
else:
try:
item = salt.utils.stringutils.to_bytes(item, encoding, errors)
except TypeError:
# to_bytes raises a TypeError when input is not a
# string/bytestring/bytearray. This is expected and simply
# means we are going to leave the value as-is.
pass
except UnicodeEncodeError:
if not keep:
raise
rv.append(item)
return rv | python | 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,
preserve_dict_class, preserve_tuples)
elif isinstance(item, tuple):
item = encode_tuple(item, encoding, errors, keep, preserve_dict_class) \
if preserve_tuples \
else encode_list(item, encoding, errors, keep,
preserve_dict_class, preserve_tuples)
elif isinstance(item, Mapping):
item = encode_dict(item, encoding, errors, keep,
preserve_dict_class, preserve_tuples)
else:
try:
item = salt.utils.stringutils.to_bytes(item, encoding, errors)
except TypeError:
# to_bytes raises a TypeError when input is not a
# string/bytestring/bytearray. This is expected and simply
# means we are going to leave the value as-is.
pass
except UnicodeEncodeError:
if not keep:
raise
rv.append(item)
return rv | [
"def",
"encode_list",
"(",
"data",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
",",
"keep",
"=",
"False",
",",
"preserve_dict_class",
"=",
"False",
",",
"preserve_tuples",
"=",
"False",
")",
":",
"rv",
"=",
"[",
"]",
"for",
"item",
"i... | Encode all string values to bytes | [
"Encode",
"all",
"string",
"values",
"to",
"bytes"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/data.py#L423-L454 | train |
saltstack/salt | salt/utils/data.py | encode_tuple | 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)) | python | 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",
"encode_tuple",
"(",
"data",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"'strict'",
",",
"keep",
"=",
"False",
",",
"preserve_dict_class",
"=",
"False",
")",
":",
"return",
"tuple",
"(",
"encode_list",
"(",
"data",
",",
"encoding",
",",
"er... | Encode all string values to Unicode | [
"Encode",
"all",
"string",
"values",
"to",
"Unicode"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/data.py#L457-L463 | train |
saltstack/salt | salt/utils/data.py | filter_by | 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
val = traverse_dict_and_list(traverse, lookup, [])
# Iterate over the list of values to match against patterns in the
# lookup_dict keys
for each in val if isinstance(val, list) else [val]:
for key in lookup_dict:
test_key = key if isinstance(key, six.string_types) \
else six.text_type(key)
test_each = each if isinstance(each, six.string_types) \
else six.text_type(each)
if fnmatch.fnmatchcase(test_each, test_key):
ret = lookup_dict[key]
break
if ret is not None:
break
if ret is None:
ret = lookup_dict.get(default, None)
if base and base in lookup_dict:
base_values = lookup_dict[base]
if ret is None:
ret = base_values
elif isinstance(base_values, Mapping):
if not isinstance(ret, Mapping):
raise SaltException(
'filter_by default and look-up values must both be '
'dictionaries.')
ret = salt.utils.dictupdate.update(copy.deepcopy(base_values), ret)
if merge:
if not isinstance(merge, Mapping):
raise SaltException(
'filter_by merge argument must be a dictionary.')
if ret is None:
ret = merge
else:
salt.utils.dictupdate.update(ret, copy.deepcopy(merge))
return ret | python | 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
val = traverse_dict_and_list(traverse, lookup, [])
# Iterate over the list of values to match against patterns in the
# lookup_dict keys
for each in val if isinstance(val, list) else [val]:
for key in lookup_dict:
test_key = key if isinstance(key, six.string_types) \
else six.text_type(key)
test_each = each if isinstance(each, six.string_types) \
else six.text_type(each)
if fnmatch.fnmatchcase(test_each, test_key):
ret = lookup_dict[key]
break
if ret is not None:
break
if ret is None:
ret = lookup_dict.get(default, None)
if base and base in lookup_dict:
base_values = lookup_dict[base]
if ret is None:
ret = base_values
elif isinstance(base_values, Mapping):
if not isinstance(ret, Mapping):
raise SaltException(
'filter_by default and look-up values must both be '
'dictionaries.')
ret = salt.utils.dictupdate.update(copy.deepcopy(base_values), ret)
if merge:
if not isinstance(merge, Mapping):
raise SaltException(
'filter_by merge argument must be a dictionary.')
if ret is None:
ret = merge
else:
salt.utils.dictupdate.update(ret, copy.deepcopy(merge))
return ret | [
"def",
"filter_by",
"(",
"lookup_dict",
",",
"lookup",
",",
"traverse",
",",
"merge",
"=",
"None",
",",
"default",
"=",
"'default'",
",",
"base",
"=",
"None",
")",
":",
"ret",
"=",
"None",
"# Default value would be an empty list if lookup not found",
"val",
"=",... | Common code to filter data structures like grains and pillar | [
"Common",
"code",
"to",
"filter",
"data",
"structures",
"like",
"grains",
"and",
"pillar"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/data.py#L484-L536 | train |
saltstack/salt | salt/utils/data.py | traverse_dict | 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
the dict in the default argument.
'''
ptr = data
try:
for each in key.split(delimiter):
ptr = ptr[each]
except (KeyError, IndexError, TypeError):
# Encountered a non-indexable value in the middle of traversing
return default
return ptr | python | 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
the dict in the default argument.
'''
ptr = data
try:
for each in key.split(delimiter):
ptr = ptr[each]
except (KeyError, IndexError, TypeError):
# Encountered a non-indexable value in the middle of traversing
return default
return ptr | [
"def",
"traverse_dict",
"(",
"data",
",",
"key",
",",
"default",
"=",
"None",
",",
"delimiter",
"=",
"DEFAULT_TARGET_DELIM",
")",
":",
"ptr",
"=",
"data",
"try",
":",
"for",
"each",
"in",
"key",
".",
"split",
"(",
"delimiter",
")",
":",
"ptr",
"=",
"... | 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. | [
"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... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/data.py#L539-L553 | train |
saltstack/salt | salt/utils/data.py | traverse_dict_and_list | 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
return the dict in the default argument.
Function will automatically determine the target type.
The target 'foo:bar:0' will return data['foo']['bar'][0] if data like
{'foo':{'bar':['baz']}} , if data like {'foo':{'bar':{'0':'baz'}}}
then return data['foo']['bar']['0']
'''
ptr = data
for each in key.split(delimiter):
if isinstance(ptr, list):
try:
idx = int(each)
except ValueError:
embed_match = False
# Index was not numeric, lets look at any embedded dicts
for embedded in (x for x in ptr if isinstance(x, dict)):
try:
ptr = embedded[each]
embed_match = True
break
except KeyError:
pass
if not embed_match:
# No embedded dicts matched, return the default
return default
else:
try:
ptr = ptr[idx]
except IndexError:
return default
else:
try:
ptr = ptr[each]
except (KeyError, TypeError):
return default
return ptr | python | 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
return the dict in the default argument.
Function will automatically determine the target type.
The target 'foo:bar:0' will return data['foo']['bar'][0] if data like
{'foo':{'bar':['baz']}} , if data like {'foo':{'bar':{'0':'baz'}}}
then return data['foo']['bar']['0']
'''
ptr = data
for each in key.split(delimiter):
if isinstance(ptr, list):
try:
idx = int(each)
except ValueError:
embed_match = False
# Index was not numeric, lets look at any embedded dicts
for embedded in (x for x in ptr if isinstance(x, dict)):
try:
ptr = embedded[each]
embed_match = True
break
except KeyError:
pass
if not embed_match:
# No embedded dicts matched, return the default
return default
else:
try:
ptr = ptr[idx]
except IndexError:
return default
else:
try:
ptr = ptr[each]
except (KeyError, TypeError):
return default
return ptr | [
"def",
"traverse_dict_and_list",
"(",
"data",
",",
"key",
",",
"default",
"=",
"None",
",",
"delimiter",
"=",
"DEFAULT_TARGET_DELIM",
")",
":",
"ptr",
"=",
"data",
"for",
"each",
"in",
"key",
".",
"split",
"(",
"delimiter",
")",
":",
"if",
"isinstance",
... | 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 type.
The target 'foo:bar:0' will return data['foo']['bar'][0] if data like
{'foo':{'bar':['baz']}} , if data like {'foo':{'bar':{'0':'baz'}}}
then return data['foo']['bar']['0'] | [
"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... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/data.py#L557-L596 | train |
saltstack/salt | salt/utils/data.py | subdict_match | 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 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-nested matches are tried first.
'''
def _match(target, pattern, regex_match=False, exact_match=False):
# The reason for using six.text_type first and _then_ using
# to_unicode as a fallback is because we want to eventually have
# unicode types for comparison below. If either value is numeric then
# six.text_type will turn it into a unicode string. However, if the
# value is a PY2 str type with non-ascii chars, then the result will be
# a UnicodeDecodeError. In those cases, we simply use to_unicode to
# decode it to unicode. The reason we can't simply use to_unicode to
# begin with is that (by design) to_unicode will raise a TypeError if a
# non-string/bytestring/bytearray value is passed.
try:
target = six.text_type(target).lower()
except UnicodeDecodeError:
target = salt.utils.stringutils.to_unicode(target).lower()
try:
pattern = six.text_type(pattern).lower()
except UnicodeDecodeError:
pattern = salt.utils.stringutils.to_unicode(pattern).lower()
if regex_match:
try:
return re.match(pattern, target)
except Exception:
log.error('Invalid regex \'%s\' in match', pattern)
return False
else:
return target == pattern if exact_match \
else fnmatch.fnmatch(target, pattern)
def _dict_match(target, pattern, regex_match=False, exact_match=False):
wildcard = pattern.startswith('*:')
if wildcard:
pattern = pattern[2:]
if pattern == '*':
# We are just checking that the key exists
return True
elif pattern in target:
# We might want to search for a key
return True
elif subdict_match(target,
pattern,
regex_match=regex_match,
exact_match=exact_match):
return True
if wildcard:
for key in target:
if isinstance(target[key], dict):
if _dict_match(target[key],
pattern,
regex_match=regex_match,
exact_match=exact_match):
return True
elif isinstance(target[key], list):
for item in target[key]:
if _match(item,
pattern,
regex_match=regex_match,
exact_match=exact_match):
return True
elif _match(target[key],
pattern,
regex_match=regex_match,
exact_match=exact_match):
return True
return False
splits = expr.split(delimiter)
num_splits = len(splits)
if num_splits == 1:
# Delimiter not present, this can't possibly be a match
return False
splits = expr.split(delimiter)
num_splits = len(splits)
if num_splits == 1:
# Delimiter not present, this can't possibly be a match
return False
# If we have 4 splits, then we have three delimiters. Thus, the indexes we
# want to use are 3, 2, and 1, in that order.
for idx in range(num_splits - 1, 0, -1):
key = delimiter.join(splits[:idx])
if key == '*':
# We are matching on everything under the top level, so we need to
# treat the match as the entire data being passed in
matchstr = expr
match = data
else:
matchstr = delimiter.join(splits[idx:])
match = traverse_dict_and_list(data, key, {}, delimiter=delimiter)
log.debug("Attempting to match '%s' in '%s' using delimiter '%s'",
matchstr, key, delimiter)
if match == {}:
continue
if isinstance(match, dict):
if _dict_match(match,
matchstr,
regex_match=regex_match,
exact_match=exact_match):
return True
continue
if isinstance(match, (list, tuple)):
# We are matching a single component to a single list member
for member in match:
if isinstance(member, dict):
if _dict_match(member,
matchstr,
regex_match=regex_match,
exact_match=exact_match):
return True
if _match(member,
matchstr,
regex_match=regex_match,
exact_match=exact_match):
return True
continue
if _match(match,
matchstr,
regex_match=regex_match,
exact_match=exact_match):
return True
return False | python | 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 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-nested matches are tried first.
'''
def _match(target, pattern, regex_match=False, exact_match=False):
# The reason for using six.text_type first and _then_ using
# to_unicode as a fallback is because we want to eventually have
# unicode types for comparison below. If either value is numeric then
# six.text_type will turn it into a unicode string. However, if the
# value is a PY2 str type with non-ascii chars, then the result will be
# a UnicodeDecodeError. In those cases, we simply use to_unicode to
# decode it to unicode. The reason we can't simply use to_unicode to
# begin with is that (by design) to_unicode will raise a TypeError if a
# non-string/bytestring/bytearray value is passed.
try:
target = six.text_type(target).lower()
except UnicodeDecodeError:
target = salt.utils.stringutils.to_unicode(target).lower()
try:
pattern = six.text_type(pattern).lower()
except UnicodeDecodeError:
pattern = salt.utils.stringutils.to_unicode(pattern).lower()
if regex_match:
try:
return re.match(pattern, target)
except Exception:
log.error('Invalid regex \'%s\' in match', pattern)
return False
else:
return target == pattern if exact_match \
else fnmatch.fnmatch(target, pattern)
def _dict_match(target, pattern, regex_match=False, exact_match=False):
wildcard = pattern.startswith('*:')
if wildcard:
pattern = pattern[2:]
if pattern == '*':
# We are just checking that the key exists
return True
elif pattern in target:
# We might want to search for a key
return True
elif subdict_match(target,
pattern,
regex_match=regex_match,
exact_match=exact_match):
return True
if wildcard:
for key in target:
if isinstance(target[key], dict):
if _dict_match(target[key],
pattern,
regex_match=regex_match,
exact_match=exact_match):
return True
elif isinstance(target[key], list):
for item in target[key]:
if _match(item,
pattern,
regex_match=regex_match,
exact_match=exact_match):
return True
elif _match(target[key],
pattern,
regex_match=regex_match,
exact_match=exact_match):
return True
return False
splits = expr.split(delimiter)
num_splits = len(splits)
if num_splits == 1:
# Delimiter not present, this can't possibly be a match
return False
splits = expr.split(delimiter)
num_splits = len(splits)
if num_splits == 1:
# Delimiter not present, this can't possibly be a match
return False
# If we have 4 splits, then we have three delimiters. Thus, the indexes we
# want to use are 3, 2, and 1, in that order.
for idx in range(num_splits - 1, 0, -1):
key = delimiter.join(splits[:idx])
if key == '*':
# We are matching on everything under the top level, so we need to
# treat the match as the entire data being passed in
matchstr = expr
match = data
else:
matchstr = delimiter.join(splits[idx:])
match = traverse_dict_and_list(data, key, {}, delimiter=delimiter)
log.debug("Attempting to match '%s' in '%s' using delimiter '%s'",
matchstr, key, delimiter)
if match == {}:
continue
if isinstance(match, dict):
if _dict_match(match,
matchstr,
regex_match=regex_match,
exact_match=exact_match):
return True
continue
if isinstance(match, (list, tuple)):
# We are matching a single component to a single list member
for member in match:
if isinstance(member, dict):
if _dict_match(member,
matchstr,
regex_match=regex_match,
exact_match=exact_match):
return True
if _match(member,
matchstr,
regex_match=regex_match,
exact_match=exact_match):
return True
continue
if _match(match,
matchstr,
regex_match=regex_match,
exact_match=exact_match):
return True
return False | [
"def",
"subdict_match",
"(",
"data",
",",
"expr",
",",
"delimiter",
"=",
"DEFAULT_TARGET_DELIM",
",",
"regex_match",
"=",
"False",
",",
"exact_match",
"=",
"False",
")",
":",
"def",
"_match",
"(",
"target",
",",
"pattern",
",",
"regex_match",
"=",
"False",
... | 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-nested matches are tried first. | [
"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",
":... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/data.py#L599-L733 | train |
saltstack/salt | salt/utils/data.py | is_dictlist | 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:
return False
else:
return False
return True
return False | python | 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:
return False
else:
return False
return True
return False | [
"def",
"is_dictlist",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"for",
"element",
"in",
"data",
":",
"if",
"isinstance",
"(",
"element",
",",
"dict",
")",
":",
"if",
"len",
"(",
"element",
")",
"!=",
"1",
":",
... | Returns True if data is a list of one-element dicts (as found in many SLS
schemas), otherwise returns False | [
"Returns",
"True",
"if",
"data",
"is",
"a",
"list",
"of",
"one",
"-",
"element",
"dicts",
"(",
"as",
"found",
"in",
"many",
"SLS",
"schemas",
")",
"otherwise",
"returns",
"False"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/data.py#L745-L758 | train |
saltstack/salt | salt/utils/data.py | repack_dictlist | 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.string_types):
try:
data = salt.utils.yaml.safe_load(data)
except salt.utils.yaml.parser.ParserError as err:
log.error(err)
return {}
if key_cb is None:
key_cb = lambda x: x
if val_cb is None:
val_cb = lambda x, y: y
valid_non_dict = (six.string_types, six.integer_types, float)
if isinstance(data, list):
for element in data:
if isinstance(element, valid_non_dict):
continue
elif isinstance(element, dict):
if len(element) != 1:
log.error(
'Invalid input for repack_dictlist: key/value pairs '
'must contain only one element (data passed: %s).',
element
)
return {}
else:
log.error(
'Invalid input for repack_dictlist: element %s is '
'not a string/dict/numeric value', element
)
return {}
else:
log.error(
'Invalid input for repack_dictlist, data passed is not a list '
'(%s)', data
)
return {}
ret = {}
for element in data:
if isinstance(element, valid_non_dict):
ret[key_cb(element)] = None
else:
key = next(iter(element))
val = element[key]
if is_dictlist(val):
if recurse:
ret[key_cb(key)] = repack_dictlist(val, recurse=recurse)
elif strict:
log.error(
'Invalid input for repack_dictlist: nested dictlist '
'found, but recurse is set to False'
)
return {}
else:
ret[key_cb(key)] = val_cb(key, val)
else:
ret[key_cb(key)] = val_cb(key, val)
return ret | python | 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.string_types):
try:
data = salt.utils.yaml.safe_load(data)
except salt.utils.yaml.parser.ParserError as err:
log.error(err)
return {}
if key_cb is None:
key_cb = lambda x: x
if val_cb is None:
val_cb = lambda x, y: y
valid_non_dict = (six.string_types, six.integer_types, float)
if isinstance(data, list):
for element in data:
if isinstance(element, valid_non_dict):
continue
elif isinstance(element, dict):
if len(element) != 1:
log.error(
'Invalid input for repack_dictlist: key/value pairs '
'must contain only one element (data passed: %s).',
element
)
return {}
else:
log.error(
'Invalid input for repack_dictlist: element %s is '
'not a string/dict/numeric value', element
)
return {}
else:
log.error(
'Invalid input for repack_dictlist, data passed is not a list '
'(%s)', data
)
return {}
ret = {}
for element in data:
if isinstance(element, valid_non_dict):
ret[key_cb(element)] = None
else:
key = next(iter(element))
val = element[key]
if is_dictlist(val):
if recurse:
ret[key_cb(key)] = repack_dictlist(val, recurse=recurse)
elif strict:
log.error(
'Invalid input for repack_dictlist: nested dictlist '
'found, but recurse is set to False'
)
return {}
else:
ret[key_cb(key)] = val_cb(key, val)
else:
ret[key_cb(key)] = val_cb(key, val)
return ret | [
"def",
"repack_dictlist",
"(",
"data",
",",
"strict",
"=",
"False",
",",
"recurse",
"=",
"False",
",",
"key_cb",
"=",
"None",
",",
"val_cb",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"six",
".",
"string_types",
")",
":",
"try",
":"... | Takes a list of one-element dicts (as found in many SLS schemas) and
repacks into a single dictionary. | [
"Takes",
"a",
"list",
"of",
"one",
"-",
"element",
"dicts",
"(",
"as",
"found",
"in",
"many",
"SLS",
"schemas",
")",
"and",
"repacks",
"into",
"a",
"single",
"dictionary",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/data.py#L761-L828 | train |
saltstack/salt | salt/utils/data.py | is_iter | 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 iterable. This can be used to also exclude things like
dictionaries or named tuples.
Based on https://bitbucket.org/petershinners/yter
'''
if ignore and isinstance(y, ignore):
return False
try:
iter(y)
return True
except TypeError:
return False | python | 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 iterable. This can be used to also exclude things like
dictionaries or named tuples.
Based on https://bitbucket.org/petershinners/yter
'''
if ignore and isinstance(y, ignore):
return False
try:
iter(y)
return True
except TypeError:
return False | [
"def",
"is_iter",
"(",
"y",
",",
"ignore",
"=",
"six",
".",
"string_types",
")",
":",
"if",
"ignore",
"and",
"isinstance",
"(",
"y",
",",
"ignore",
")",
":",
"return",
"False",
"try",
":",
"iter",
"(",
"y",
")",
"return",
"True",
"except",
"TypeError... | 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
dictionaries or named tuples.
Based on https://bitbucket.org/petershinners/yter | [
"Test",
"if",
"an",
"object",
"is",
"iterable",
"but",
"not",
"a",
"string",
"type",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/data.py#L840-L860 | train |
saltstack/salt | salt/utils/data.py | is_true | 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
'''
# First, try int/float conversion
try:
value = int(value)
except (ValueError, TypeError):
pass
try:
value = float(value)
except (ValueError, TypeError):
pass
# Now check for truthiness
if isinstance(value, (six.integer_types, float)):
return value > 0
elif isinstance(value, six.string_types):
return six.text_type(value).lower() == 'true'
else:
return bool(value) | python | 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
'''
# First, try int/float conversion
try:
value = int(value)
except (ValueError, TypeError):
pass
try:
value = float(value)
except (ValueError, TypeError):
pass
# Now check for truthiness
if isinstance(value, (six.integer_types, float)):
return value > 0
elif isinstance(value, six.string_types):
return six.text_type(value).lower() == 'true'
else:
return bool(value) | [
"def",
"is_true",
"(",
"value",
"=",
"None",
")",
":",
"# First, try int/float conversion",
"try",
":",
"value",
"=",
"int",
"(",
"value",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"pass",
"try",
":",
"value",
"=",
"float",
"(",
"valu... | 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 | [
"Returns",
"a",
"boolean",
"value",
"representing",
"the",
"truth",
"of",
"the",
"value",
"passed",
".",
"The",
"rules",
"for",
"what",
"is",
"a",
"True",
"value",
"are",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/data.py#L878-L903 | train |
saltstack/salt | salt/utils/data.py | mysql_to_dict | 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)):
comps[comp] = comps[comp].strip()
if len(headers) > 1:
index = len(headers) - 1
row = {}
for field in range(index):
if field < 1:
continue
else:
row[headers[field]] = salt.utils.stringutils.to_num(comps[field])
ret[row[key]] = row
else:
headers = comps
return ret | python | 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)):
comps[comp] = comps[comp].strip()
if len(headers) > 1:
index = len(headers) - 1
row = {}
for field in range(index):
if field < 1:
continue
else:
row[headers[field]] = salt.utils.stringutils.to_num(comps[field])
ret[row[key]] = row
else:
headers = comps
return ret | [
"def",
"mysql_to_dict",
"(",
"data",
",",
"key",
")",
":",
"ret",
"=",
"{",
"}",
"headers",
"=",
"[",
"''",
"]",
"for",
"line",
"in",
"data",
":",
"if",
"not",
"line",
":",
"continue",
"if",
"line",
".",
"startswith",
"(",
"'+'",
")",
":",
"conti... | Convert MySQL-style output to a python dictionary | [
"Convert",
"MySQL",
"-",
"style",
"output",
"to",
"a",
"python",
"dictionary"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/data.py#L907-L932 | train |
saltstack/salt | salt/utils/data.py | simple_types_filter | 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(simpletypes_keys) + [list, tuple])
if isinstance(data, (list, tuple)):
simplearray = []
for value in data:
if value is not None:
if isinstance(value, (dict, list)):
value = simple_types_filter(value)
elif not isinstance(value, simpletypes_values):
value = repr(value)
simplearray.append(value)
return simplearray
if isinstance(data, dict):
simpledict = {}
for key, value in six.iteritems(data):
if key is not None and not isinstance(key, simpletypes_keys):
key = repr(key)
if value is not None and isinstance(value, (dict, list, tuple)):
value = simple_types_filter(value)
elif value is not None and not isinstance(value, simpletypes_values):
value = repr(value)
simpledict[key] = value
return simpledict
return data | python | 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(simpletypes_keys) + [list, tuple])
if isinstance(data, (list, tuple)):
simplearray = []
for value in data:
if value is not None:
if isinstance(value, (dict, list)):
value = simple_types_filter(value)
elif not isinstance(value, simpletypes_values):
value = repr(value)
simplearray.append(value)
return simplearray
if isinstance(data, dict):
simpledict = {}
for key, value in six.iteritems(data):
if key is not None and not isinstance(key, simpletypes_keys):
key = repr(key)
if value is not None and isinstance(value, (dict, list, tuple)):
value = simple_types_filter(value)
elif value is not None and not isinstance(value, simpletypes_values):
value = repr(value)
simpledict[key] = value
return simpledict
return data | [
"def",
"simple_types_filter",
"(",
"data",
")",
":",
"if",
"data",
"is",
"None",
":",
"return",
"data",
"simpletypes_keys",
"=",
"(",
"six",
".",
"string_types",
",",
"six",
".",
"text_type",
",",
"six",
".",
"integer_types",
",",
"float",
",",
"bool",
"... | Convert the data list, dictionary into simple types, i.e., int, float, string,
bool, etc. | [
"Convert",
"the",
"data",
"list",
"dictionary",
"into",
"simple",
"types",
"i",
".",
"e",
".",
"int",
"float",
"string",
"bool",
"etc",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/data.py#L935-L969 | train |
saltstack/salt | salt/utils/data.py | stringify | 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(item, six.string_types):
item = six.text_type(item)
ret.append(item)
return ret | python | 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(item, six.string_types):
item = six.text_type(item)
ret.append(item)
return ret | [
"def",
"stringify",
"(",
"data",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"item",
"in",
"data",
":",
"if",
"six",
".",
"PY2",
"and",
"isinstance",
"(",
"item",
",",
"str",
")",
":",
"item",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_un... | Given an iterable, returns its items as a list, with any non-string items
converted to unicode strings. | [
"Given",
"an",
"iterable",
"returns",
"its",
"items",
"as",
"a",
"list",
"with",
"any",
"non",
"-",
"string",
"items",
"converted",
"to",
"unicode",
"strings",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/data.py#L972-L984 | train |
saltstack/salt | salt/utils/data.py | json_query | 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) | python | 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",
"json_query",
"(",
"data",
",",
"expr",
")",
":",
"if",
"jmespath",
"is",
"None",
":",
"err",
"=",
"'json_query requires jmespath module installed'",
"log",
".",
"error",
"(",
"err",
")",
"raise",
"RuntimeError",
"(",
"err",
")",
"return",
"jmespath",
... | Query data using JMESPath language (http://jmespath.org). | [
"Query",
"data",
"using",
"JMESPath",
"language",
"(",
"http",
":",
"//",
"jmespath",
".",
"org",
")",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/data.py#L988-L996 | train |
saltstack/salt | salt/utils/data.py | _is_not_considered_falsey | 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
'''
return isinstance(value, bool) or type(value) in ignore_types or value | python | 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
'''
return isinstance(value, bool) or type(value) in ignore_types or value | [
"def",
"_is_not_considered_falsey",
"(",
"value",
",",
"ignore_types",
"=",
"(",
")",
")",
":",
"return",
"isinstance",
"(",
"value",
",",
"bool",
")",
"or",
"type",
"(",
"value",
")",
"in",
"ignore_types",
"or",
"value"
] | 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 | [
"Helper",
"function",
"for",
"filter_falsey",
"to",
"determine",
"if",
"something",
"is",
"not",
"to",
"be",
"considered",
"falsey",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/data.py#L999-L1009 | train |
saltstack/salt | salt/utils/data.py | filter_falsey | 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: Source iterable (dict, OrderedDict, list, set, ...) to process.
:param int recurse_depth: Recurse this many levels into values that are dicts
or lists to also process those. Default: 0 (do not recurse)
:param list ignore_types: Contains types that can be falsey but must not
be filtered. Default: Only booleans are not filtered.
:return type(data)
.. version-added:: Neon
'''
filter_element = (
functools.partial(filter_falsey,
recurse_depth=recurse_depth-1,
ignore_types=ignore_types)
if recurse_depth else lambda x: x
)
if isinstance(data, dict):
processed_elements = [(key, filter_element(value)) for key, value in six.iteritems(data)]
return type(data)([
(key, value)
for key, value in processed_elements
if _is_not_considered_falsey(value, ignore_types=ignore_types)
])
elif hasattr(data, '__iter__') and not isinstance(data, six.string_types):
processed_elements = (filter_element(value) for value in data)
return type(data)([
value for value in processed_elements
if _is_not_considered_falsey(value, ignore_types=ignore_types)
])
return data | python | 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: Source iterable (dict, OrderedDict, list, set, ...) to process.
:param int recurse_depth: Recurse this many levels into values that are dicts
or lists to also process those. Default: 0 (do not recurse)
:param list ignore_types: Contains types that can be falsey but must not
be filtered. Default: Only booleans are not filtered.
:return type(data)
.. version-added:: Neon
'''
filter_element = (
functools.partial(filter_falsey,
recurse_depth=recurse_depth-1,
ignore_types=ignore_types)
if recurse_depth else lambda x: x
)
if isinstance(data, dict):
processed_elements = [(key, filter_element(value)) for key, value in six.iteritems(data)]
return type(data)([
(key, value)
for key, value in processed_elements
if _is_not_considered_falsey(value, ignore_types=ignore_types)
])
elif hasattr(data, '__iter__') and not isinstance(data, six.string_types):
processed_elements = (filter_element(value) for value in data)
return type(data)([
value for value in processed_elements
if _is_not_considered_falsey(value, ignore_types=ignore_types)
])
return data | [
"def",
"filter_falsey",
"(",
"data",
",",
"recurse_depth",
"=",
"None",
",",
"ignore_types",
"=",
"(",
")",
")",
":",
"filter_element",
"=",
"(",
"functools",
".",
"partial",
"(",
"filter_falsey",
",",
"recurse_depth",
"=",
"recurse_depth",
"-",
"1",
",",
... | 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 int recurse_depth: Recurse this many levels into values that are dicts
or lists to also process those. Default: 0 (do not recurse)
:param list ignore_types: Contains types that can be falsey but must not
be filtered. Default: Only booleans are not filtered.
:return type(data)
.. version-added:: Neon | [
"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",... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/data.py#L1012-L1048 | train |
saltstack/salt | salt/utils/data.py | CaseInsensitiveDict.items_lower | 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)) | python | 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",
"items_lower",
"(",
"self",
")",
":",
"return",
"(",
"(",
"key",
",",
"val",
"[",
"1",
"]",
")",
"for",
"key",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"_data",
")",
")"
] | Returns a generator iterating over keys and values, with the keys all
being lowercase. | [
"Returns",
"a",
"generator",
"iterating",
"over",
"keys",
"and",
"values",
"with",
"the",
"keys",
"all",
"being",
"lowercase",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/data.py#L80-L85 | train |
saltstack/salt | salt/states/macdefaults.py | write | 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, valid types are string, data, int[eger],
float, bool[ean], date, array, array-add, dict, dict-add
user
The user to write the defaults to
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}}
def safe_cast(val, to_type, default=None):
try:
return to_type(val)
except ValueError:
return default
current_value = __salt__['macdefaults.read'](domain, name, user)
if (vtype in ['bool', 'boolean']) and ((value in [True, 'TRUE', 'YES'] and current_value == '1') or
(value in [False, 'FALSE', 'NO'] and current_value == '0')):
ret['comment'] += '{0} {1} is already set to {2}'.format(domain, name, value)
elif vtype in ['int', 'integer'] and safe_cast(current_value, int) == safe_cast(value, int):
ret['comment'] += '{0} {1} is already set to {2}'.format(domain, name, value)
elif current_value == value:
ret['comment'] += '{0} {1} is already set to {2}'.format(domain, name, value)
else:
out = __salt__['macdefaults.write'](domain, name, value, vtype, user)
if out['retcode'] != 0:
ret['result'] = False
ret['comment'] = 'Failed to write default. {0}'.format(out['stdout'])
else:
ret['changes']['written'] = '{0} {1} is set to {2}'.format(domain, name, value)
return ret | python | 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, valid types are string, data, int[eger],
float, bool[ean], date, array, array-add, dict, dict-add
user
The user to write the defaults to
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}}
def safe_cast(val, to_type, default=None):
try:
return to_type(val)
except ValueError:
return default
current_value = __salt__['macdefaults.read'](domain, name, user)
if (vtype in ['bool', 'boolean']) and ((value in [True, 'TRUE', 'YES'] and current_value == '1') or
(value in [False, 'FALSE', 'NO'] and current_value == '0')):
ret['comment'] += '{0} {1} is already set to {2}'.format(domain, name, value)
elif vtype in ['int', 'integer'] and safe_cast(current_value, int) == safe_cast(value, int):
ret['comment'] += '{0} {1} is already set to {2}'.format(domain, name, value)
elif current_value == value:
ret['comment'] += '{0} {1} is already set to {2}'.format(domain, name, value)
else:
out = __salt__['macdefaults.write'](domain, name, value, vtype, user)
if out['retcode'] != 0:
ret['result'] = False
ret['comment'] = 'Failed to write default. {0}'.format(out['stdout'])
else:
ret['changes']['written'] = '{0} {1} is set to {2}'.format(domain, name, value)
return ret | [
"def",
"write",
"(",
"name",
",",
"domain",
",",
"value",
",",
"vtype",
"=",
"'string'",
",",
"user",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
... | 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], date, array, array-add, dict, dict-add
user
The user to write the defaults to | [
"Write",
"a",
"default",
"to",
"the",
"system"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/macdefaults.py#L28-L78 | train |
saltstack/salt | salt/states/macdefaults.py | absent | 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,
'comment': '',
'changes': {}}
out = __salt__['macdefaults.delete'](domain, name, user)
if out['retcode'] != 0:
ret['comment'] += "{0} {1} is already absent".format(domain, name)
else:
ret['changes']['absent'] = "{0} {1} is now absent".format(domain, name)
return ret | python | 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,
'comment': '',
'changes': {}}
out = __salt__['macdefaults.delete'](domain, name, user)
if out['retcode'] != 0:
ret['comment'] += "{0} {1} is already absent".format(domain, name)
else:
ret['changes']['absent'] = "{0} {1} is now absent".format(domain, name)
return ret | [
"def",
"absent",
"(",
"name",
",",
"domain",
",",
"user",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"out",
"=",
"__salt__",
"[",... | 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 | [
"Make",
"sure",
"the",
"defaults",
"value",
"is",
"absent"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/macdefaults.py#L81-L108 | train |
saltstack/salt | salt/modules/win_shadow.py | info | 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=name)
ret = {'name': name,
'passwd': '',
'lstchg': '',
'min': '',
'max': '',
'warn': '',
'inact': '',
'expire': ''}
if info:
ret = {'name': info['name'],
'passwd': 'Unavailable',
'lstchg': info['password_changed'],
'min': '',
'max': '',
'warn': '',
'inact': '',
'expire': info['expiration_date']}
return ret | python | 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=name)
ret = {'name': name,
'passwd': '',
'lstchg': '',
'min': '',
'max': '',
'warn': '',
'inact': '',
'expire': ''}
if info:
ret = {'name': info['name'],
'passwd': 'Unavailable',
'lstchg': info['password_changed'],
'min': '',
'max': '',
'warn': '',
'inact': '',
'expire': info['expiration_date']}
return ret | [
"def",
"info",
"(",
"name",
")",
":",
"info",
"=",
"__salt__",
"[",
"'user.info'",
"]",
"(",
"name",
"=",
"name",
")",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'passwd'",
":",
"''",
",",
"'lstchg'",
":",
"''",
",",
"'min'",
":",
"''",
",",
... | 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 | [
"Return",
"information",
"for",
"the",
"specified",
"user",
"This",
"is",
"just",
"returns",
"dummy",
"data",
"so",
"that",
"salt",
"states",
"can",
"work",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_shadow.py#L30-L64 | train |
saltstack/salt | salt/utils/saltclass.py | get_class_paths | 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(str)
'''
straight = os.path.join(saltclass_path,
'classes',
'{0}.yml'.format(_class))
sub_straight = os.path.join(saltclass_path,
'classes',
'{0}.yml'.format(_class.replace('.', os.sep)))
sub_init = os.path.join(saltclass_path,
'classes',
_class.replace('.', os.sep),
'init.yml')
return straight, sub_init, sub_straight | python | 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(str)
'''
straight = os.path.join(saltclass_path,
'classes',
'{0}.yml'.format(_class))
sub_straight = os.path.join(saltclass_path,
'classes',
'{0}.yml'.format(_class.replace('.', os.sep)))
sub_init = os.path.join(saltclass_path,
'classes',
_class.replace('.', os.sep),
'init.yml')
return straight, sub_init, sub_straight | [
"def",
"get_class_paths",
"(",
"_class",
",",
"saltclass_path",
")",
":",
"straight",
"=",
"os",
".",
"path",
".",
"join",
"(",
"saltclass_path",
",",
"'classes'",
",",
"'{0}.yml'",
".",
"format",
"(",
"_class",
")",
")",
"sub_straight",
"=",
"os",
".",
... | 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) | [
"Converts",
"the",
"dotted",
"notation",
"of",
"a",
"saltclass",
"class",
"to",
"its",
"possible",
"file",
"counterparts",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/saltclass.py#L64-L83 | train |
saltstack/salt | salt/utils/saltclass.py | get_class_from_file | 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: Absolute path to file
:param str saltclass_path: Root to saltclass storage
:return: class name in dotted notation
:rtype: str
'''
# remove classes path prefix
_file = _file[len(os.path.join(saltclass_path, 'classes')) + len(os.sep):]
# remove .yml extension
_file = _file[:-4]
# revert to dotted notation
_file = _file.replace(os.sep, '.')
# remove tailing init
if _file.endswith('.init'):
_file = _file[:-5]
return _file | python | 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: Absolute path to file
:param str saltclass_path: Root to saltclass storage
:return: class name in dotted notation
:rtype: str
'''
# remove classes path prefix
_file = _file[len(os.path.join(saltclass_path, 'classes')) + len(os.sep):]
# remove .yml extension
_file = _file[:-4]
# revert to dotted notation
_file = _file.replace(os.sep, '.')
# remove tailing init
if _file.endswith('.init'):
_file = _file[:-5]
return _file | [
"def",
"get_class_from_file",
"(",
"_file",
",",
"saltclass_path",
")",
":",
"# remove classes path prefix",
"_file",
"=",
"_file",
"[",
"len",
"(",
"os",
".",
"path",
".",
"join",
"(",
"saltclass_path",
",",
"'classes'",
")",
")",
"+",
"len",
"(",
"os",
"... | 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 saltclass storage
:return: class name in dotted notation
:rtype: str | [
"Converts",
"the",
"absolute",
"path",
"to",
"a",
"saltclass",
"file",
"back",
"to",
"the",
"dotted",
"notation",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/saltclass.py#L86-L109 | train |
saltstack/salt | salt/utils/saltclass.py | match_class_glob | 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/saltclass')
print(classes)
# services.mariadb
# services.nginx...
:param str _class: dotted class name, globbing allowed.
:param str saltclass_path: path to the saltclass root directory.
:return: The list of expanded class matches.
:rtype: list(str)
'''
straight, sub_init, sub_straight = get_class_paths(_class, saltclass_path)
classes = []
matches = []
matches.extend(glob.glob(straight))
matches.extend(glob.glob(sub_straight))
matches.extend(glob.glob(sub_init))
if not matches:
log.warning('%s: Class globbing did not yield any results', _class)
for match in matches:
classes.append(get_class_from_file(match, saltclass_path))
return classes | python | 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/saltclass')
print(classes)
# services.mariadb
# services.nginx...
:param str _class: dotted class name, globbing allowed.
:param str saltclass_path: path to the saltclass root directory.
:return: The list of expanded class matches.
:rtype: list(str)
'''
straight, sub_init, sub_straight = get_class_paths(_class, saltclass_path)
classes = []
matches = []
matches.extend(glob.glob(straight))
matches.extend(glob.glob(sub_straight))
matches.extend(glob.glob(sub_init))
if not matches:
log.warning('%s: Class globbing did not yield any results', _class)
for match in matches:
classes.append(get_class_from_file(match, saltclass_path))
return classes | [
"def",
"match_class_glob",
"(",
"_class",
",",
"saltclass_path",
")",
":",
"straight",
",",
"sub_init",
",",
"sub_straight",
"=",
"get_class_paths",
"(",
"_class",
",",
"saltclass_path",
")",
"classes",
"=",
"[",
"]",
"matches",
"=",
"[",
"]",
"matches",
"."... | 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
# services.nginx...
:param str _class: dotted class name, globbing allowed.
:param str saltclass_path: path to the saltclass root directory.
:return: The list of expanded class matches.
:rtype: list(str) | [
"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",
"wildcar... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/saltclass.py#L231-L260 | train |
saltstack/salt | salt/utils/saltclass.py | expand_classes_glob | 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_classes = []
expanded_classes = []
saltclass_path = salt_data['path']
for _class in classes:
all_classes.extend(match_class_glob(_class, saltclass_path))
for _class in all_classes:
if _class not in expanded_classes:
expanded_classes.append(_class)
return expanded_classes | python | 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_classes = []
expanded_classes = []
saltclass_path = salt_data['path']
for _class in classes:
all_classes.extend(match_class_glob(_class, saltclass_path))
for _class in all_classes:
if _class not in expanded_classes:
expanded_classes.append(_class)
return expanded_classes | [
"def",
"expand_classes_glob",
"(",
"classes",
",",
"salt_data",
")",
":",
"all_classes",
"=",
"[",
"]",
"expanded_classes",
"=",
"[",
"]",
"saltclass_path",
"=",
"salt_data",
"[",
"'path'",
"]",
"for",
"_class",
"in",
"classes",
":",
"all_classes",
".",
"ext... | 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) | [
"Expand",
"the",
"list",
"of",
"classes",
"to",
"no",
"longer",
"include",
"any",
"globbing",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/saltclass.py#L263-L283 | train |
saltstack/salt | salt/modules/syslog_ng.py | _is_simple_type | 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) | python | 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",
"_is_simple_type",
"(",
"value",
")",
":",
"return",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
"or",
"isinstance",
"(",
"value",
",",
"int",
")",
"or",
"isinstance",
"(",
"value",
",",
"float",
")",
"or",
"isinstance",
"(",... | Returns True, if the given parameter value is an instance of either
int, str, float or bool. | [
"Returns",
"True",
"if",
"the",
"given",
"parameter",
"value",
"is",
"an",
"instance",
"of",
"either",
"int",
"str",
"float",
"or",
"bool",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L425-L430 | train |
saltstack/salt | salt/modules/syslog_ng.py | _get_type_id_options | 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))
id_ = name
options = configuration[type_]
return type_, id_, options | python | 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))
id_ = name
options = configuration[type_]
return type_, id_, options | [
"def",
"_get_type_id_options",
"(",
"name",
",",
"configuration",
")",
":",
"# it's in a form of source.name",
"if",
"'.'",
"in",
"name",
":",
"type_",
",",
"sep",
",",
"id_",
"=",
"name",
".",
"partition",
"(",
"'.'",
")",
"options",
"=",
"configuration",
"... | Returns the type, id and option of a configuration object. | [
"Returns",
"the",
"type",
"id",
"and",
"option",
"of",
"a",
"configuration",
"object",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L433-L446 | train |
saltstack/salt | salt/modules/syslog_ng.py | _expand_one_key_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 | python | 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",
"_expand_one_key_dictionary",
"(",
"_dict",
")",
":",
"key",
"=",
"next",
"(",
"six",
".",
"iterkeys",
"(",
"_dict",
")",
")",
"value",
"=",
"_dict",
"[",
"key",
"]",
"return",
"key",
",",
"value"
] | Returns the only one key and it's value from a dictionary. | [
"Returns",
"the",
"only",
"one",
"key",
"and",
"it",
"s",
"value",
"from",
"a",
"dictionary",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L449-L455 | train |
saltstack/salt | salt/modules/syslog_ng.py | _parse_typed_parameter_typed_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)
elif isinstance(value, list):
for idx in value:
arg = Argument(idx)
_current_parameter_value.add_argument(arg) | python | 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)
elif isinstance(value, list):
for idx in value:
arg = Argument(idx)
_current_parameter_value.add_argument(arg) | [
"def",
"_parse_typed_parameter_typed_value",
"(",
"values",
")",
":",
"type_",
",",
"value",
"=",
"_expand_one_key_dictionary",
"(",
"values",
")",
"_current_parameter_value",
".",
"type",
"=",
"type_",
"if",
"_is_simple_type",
"(",
"value",
")",
":",
"arg",
"=",
... | Creates Arguments in a TypedParametervalue. | [
"Creates",
"Arguments",
"in",
"a",
"TypedParametervalue",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L458-L471 | train |
saltstack/salt | salt/modules/syslog_ng.py | _parse_typed_parameter | 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 = SimpleParameterValue(value)
_current_parameter.add_value(_current_parameter_value)
elif isinstance(value, list):
for i in value:
if _is_simple_type(i):
_current_parameter_value = SimpleParameterValue(i)
_current_parameter.add_value(_current_parameter_value)
elif isinstance(i, dict):
_current_parameter_value = TypedParameterValue()
_parse_typed_parameter_typed_value(i)
_current_parameter.add_value(_current_parameter_value) | python | 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 = SimpleParameterValue(value)
_current_parameter.add_value(_current_parameter_value)
elif isinstance(value, list):
for i in value:
if _is_simple_type(i):
_current_parameter_value = SimpleParameterValue(i)
_current_parameter.add_value(_current_parameter_value)
elif isinstance(i, dict):
_current_parameter_value = TypedParameterValue()
_parse_typed_parameter_typed_value(i)
_current_parameter.add_value(_current_parameter_value) | [
"def",
"_parse_typed_parameter",
"(",
"param",
")",
":",
"global",
"_current_parameter_value",
"type_",
",",
"value",
"=",
"_expand_one_key_dictionary",
"(",
"param",
")",
"_current_parameter",
".",
"type",
"=",
"type_",
"if",
"_is_simple_type",
"(",
"value",
")",
... | Parses a TypedParameter and fills it with values. | [
"Parses",
"a",
"TypedParameter",
"and",
"fills",
"it",
"with",
"values",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L474-L493 | train |
saltstack/salt | salt/modules/syslog_ng.py | _create_and_add_parameters | 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 list
for i in params:
if _is_simple_type(i):
_current_parameter = SimpleParameter(i)
else:
_current_parameter = TypedParameter()
_parse_typed_parameter(i)
_current_option.add_parameter(_current_parameter) | python | 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 list
for i in params:
if _is_simple_type(i):
_current_parameter = SimpleParameter(i)
else:
_current_parameter = TypedParameter()
_parse_typed_parameter(i)
_current_option.add_parameter(_current_parameter) | [
"def",
"_create_and_add_parameters",
"(",
"params",
")",
":",
"global",
"_current_parameter",
"if",
"_is_simple_type",
"(",
"params",
")",
":",
"_current_parameter",
"=",
"SimpleParameter",
"(",
"params",
")",
"_current_option",
".",
"add_parameter",
"(",
"_current_pa... | Parses the configuration and creates Parameter instances. | [
"Parses",
"the",
"configuration",
"and",
"creates",
"Parameter",
"instances",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L496-L512 | train |
saltstack/salt | salt/modules/syslog_ng.py | _create_and_add_option | 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_statement.add_child(_current_option) | python | 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_statement.add_child(_current_option) | [
"def",
"_create_and_add_option",
"(",
"option",
")",
":",
"global",
"_current_option",
"_current_option",
"=",
"Option",
"(",
")",
"type_",
",",
"params",
"=",
"_expand_one_key_dictionary",
"(",
"option",
")",
"_current_option",
".",
"type",
"=",
"type_",
"_create... | Parses the configuration and creates an Option instance. | [
"Parses",
"the",
"configuration",
"and",
"creates",
"an",
"Option",
"instance",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L515-L525 | train |
saltstack/salt | salt/modules/syslog_ng.py | _is_reference | 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) | python | 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_reference",
"(",
"arg",
")",
":",
"return",
"isinstance",
"(",
"arg",
",",
"dict",
")",
"and",
"len",
"(",
"arg",
")",
"==",
"1",
"and",
"isinstance",
"(",
"next",
"(",
"six",
".",
"itervalues",
"(",
"arg",
")",
")",
",",
"six",
".",
... | Return True, if arg is a reference to a previously defined statement. | [
"Return",
"True",
"if",
"arg",
"is",
"a",
"reference",
"to",
"a",
"previously",
"defined",
"statement",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L536-L540 | train |
saltstack/salt | salt/modules/syslog_ng.py | _is_junction | 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' | python | 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",
"_is_junction",
"(",
"arg",
")",
":",
"return",
"isinstance",
"(",
"arg",
",",
"dict",
")",
"and",
"len",
"(",
"arg",
")",
"==",
"1",
"and",
"next",
"(",
"six",
".",
"iterkeys",
"(",
"arg",
")",
")",
"==",
"'junction'"
] | Return True, if arg is a junction statement. | [
"Return",
"True",
"if",
"arg",
"is",
"a",
"junction",
"statement",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L543-L547 | train |
saltstack/salt | salt/modules/syslog_ng.py | _add_reference | 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) | python | 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",
"_add_reference",
"(",
"reference",
",",
"statement",
")",
":",
"type_",
",",
"value",
"=",
"_expand_one_key_dictionary",
"(",
"reference",
")",
"opt",
"=",
"Option",
"(",
"type_",
")",
"param",
"=",
"SimpleParameter",
"(",
"value",
")",
"opt",
".",
... | Adds a reference to statement. | [
"Adds",
"a",
"reference",
"to",
"statement",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L550-L558 | train |
saltstack/salt | salt/modules/syslog_ng.py | _is_inline_definition | 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) | python | 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",
"_is_inline_definition",
"(",
"arg",
")",
":",
"return",
"isinstance",
"(",
"arg",
",",
"dict",
")",
"and",
"len",
"(",
"arg",
")",
"==",
"1",
"and",
"isinstance",
"(",
"next",
"(",
"six",
".",
"itervalues",
"(",
"arg",
")",
")",
",",
"list",
... | Returns True, if arg is an inline definition of a statement. | [
"Returns",
"True",
"if",
"arg",
"is",
"an",
"inline",
"definition",
"of",
"a",
"statement",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L561-L565 | train |
saltstack/salt | salt/modules/syslog_ng.py | _add_inline_definition | 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.add_child(_current_statement)
_current_statement = backup | python | 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.add_child(_current_statement)
_current_statement = backup | [
"def",
"_add_inline_definition",
"(",
"item",
",",
"statement",
")",
":",
"global",
"_current_statement",
"backup",
"=",
"_current_statement",
"type_",
",",
"options",
"=",
"_expand_one_key_dictionary",
"(",
"item",
")",
"_current_statement",
"=",
"UnnamedStatement",
... | Adds an inline definition to statement. | [
"Adds",
"an",
"inline",
"definition",
"to",
"statement",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L568-L580 | train |
saltstack/salt | salt/modules/syslog_ng.py | _add_junction | 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='channel')
for val in value:
if _is_reference(val):
_add_reference(val, channel)
elif _is_inline_definition(val):
_add_inline_definition(val, channel)
junction.add_child(channel)
_current_statement.add_child(junction) | python | 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='channel')
for val in value:
if _is_reference(val):
_add_reference(val, channel)
elif _is_inline_definition(val):
_add_inline_definition(val, channel)
junction.add_child(channel)
_current_statement.add_child(junction) | [
"def",
"_add_junction",
"(",
"item",
")",
":",
"type_",
",",
"channels",
"=",
"_expand_one_key_dictionary",
"(",
"item",
")",
"junction",
"=",
"UnnamedStatement",
"(",
"type",
"=",
"'junction'",
")",
"for",
"item",
"in",
"channels",
":",
"type_",
",",
"value... | Adds a junction to the _current_statement. | [
"Adds",
"a",
"junction",
"to",
"the",
"_current_statement",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L583-L598 | train |
saltstack/salt | salt/modules/syslog_ng.py | _parse_log_statement | 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_statement) | python | 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_statement) | [
"def",
"_parse_log_statement",
"(",
"options",
")",
":",
"for",
"i",
"in",
"options",
":",
"if",
"_is_reference",
"(",
"i",
")",
":",
"_add_reference",
"(",
"i",
",",
"_current_statement",
")",
"elif",
"_is_junction",
"(",
"i",
")",
":",
"_add_junction",
"... | Parses a log path. | [
"Parses",
"a",
"log",
"path",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L601-L611 | train |
saltstack/salt | salt/modules/syslog_ng.py | _build_config_tree | 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 = GivenStatement(options)
elif type_ == 'log':
_current_statement = UnnamedStatement(type='log')
_parse_log_statement(options)
else:
if _is_statement_unnamed(type_):
_current_statement = UnnamedStatement(type=type_)
else:
_current_statement = NamedStatement(type=type_, id=id_)
_parse_statement(options) | python | 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 = GivenStatement(options)
elif type_ == 'log':
_current_statement = UnnamedStatement(type='log')
_parse_log_statement(options)
else:
if _is_statement_unnamed(type_):
_current_statement = UnnamedStatement(type=type_)
else:
_current_statement = NamedStatement(type=type_, id=id_)
_parse_statement(options) | [
"def",
"_build_config_tree",
"(",
"name",
",",
"configuration",
")",
":",
"type_",
",",
"id_",
",",
"options",
"=",
"_get_type_id_options",
"(",
"name",
",",
"configuration",
")",
"global",
"_INDENT",
",",
"_current_statement",
"_INDENT",
"=",
"''",
"if",
"typ... | Build the configuration tree.
The root object is _current_statement. | [
"Build",
"the",
"configuration",
"tree",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L614-L633 | train |
saltstack/salt | salt/modules/syslog_ng.py | config | 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
write : if True, it writes the config into the configuration file,
otherwise just returns it
CLI Example:
.. code-block:: bash
salt '*' syslog_ng.config name='s_local' config="[{'tcp':[{'ip':'127.0.0.1'},{'port':1233}]}]"
'''
_build_config_tree(name, config)
configs = _render_configuration()
if __opts__.get('test', False):
comment = 'State syslog_ng will write \'{0}\' into {1}'.format(
configs,
__SYSLOG_NG_CONFIG_FILE
)
return _format_state_result(name, result=None, comment=comment)
succ = write
if write:
succ = _write_config(config=configs)
return _format_state_result(name, result=succ,
changes={'new': configs, 'old': ''}) | python | 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
write : if True, it writes the config into the configuration file,
otherwise just returns it
CLI Example:
.. code-block:: bash
salt '*' syslog_ng.config name='s_local' config="[{'tcp':[{'ip':'127.0.0.1'},{'port':1233}]}]"
'''
_build_config_tree(name, config)
configs = _render_configuration()
if __opts__.get('test', False):
comment = 'State syslog_ng will write \'{0}\' into {1}'.format(
configs,
__SYSLOG_NG_CONFIG_FILE
)
return _format_state_result(name, result=None, comment=comment)
succ = write
if write:
succ = _write_config(config=configs)
return _format_state_result(name, result=succ,
changes={'new': configs, 'old': ''}) | [
"def",
"config",
"(",
"name",
",",
"config",
",",
"write",
"=",
"True",
")",
":",
"_build_config_tree",
"(",
"name",
",",
"config",
")",
"configs",
"=",
"_render_configuration",
"(",
")",
"if",
"__opts__",
".",
"get",
"(",
"'test'",
",",
"False",
")",
... | 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,
otherwise just returns it
CLI Example:
.. code-block:: bash
salt '*' syslog_ng.config name='s_local' config="[{'tcp':[{'ip':'127.0.0.1'},{'port':1233}]}]" | [
"Builds",
"syslog",
"-",
"ng",
"configuration",
".",
"This",
"function",
"is",
"intended",
"to",
"be",
"used",
"from",
"the",
"state",
"module",
"users",
"should",
"not",
"use",
"it",
"directly!"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L645-L680 | train |
saltstack/salt | salt/modules/syslog_ng.py | set_binary_path | 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.set_binary_path name=/usr/sbin
'''
global __SYSLOG_NG_BINARY_PATH
old = __SYSLOG_NG_BINARY_PATH
__SYSLOG_NG_BINARY_PATH = name
changes = _format_changes(old, name)
return _format_state_result(name, result=True, changes=changes) | python | 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.set_binary_path name=/usr/sbin
'''
global __SYSLOG_NG_BINARY_PATH
old = __SYSLOG_NG_BINARY_PATH
__SYSLOG_NG_BINARY_PATH = name
changes = _format_changes(old, name)
return _format_state_result(name, result=True, changes=changes) | [
"def",
"set_binary_path",
"(",
"name",
")",
":",
"global",
"__SYSLOG_NG_BINARY_PATH",
"old",
"=",
"__SYSLOG_NG_BINARY_PATH",
"__SYSLOG_NG_BINARY_PATH",
"=",
"name",
"changes",
"=",
"_format_changes",
"(",
"old",
",",
"name",
")",
"return",
"_format_state_result",
"(",... | 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 | [
"Sets",
"the",
"path",
"where",
"the",
"syslog",
"-",
"ng",
"binary",
"can",
"be",
"found",
".",
"This",
"function",
"is",
"intended",
"to",
"be",
"used",
"from",
"states",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L683-L702 | train |
saltstack/salt | salt/modules/syslog_ng.py | set_config_file | 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
__SYSLOG_NG_CONFIG_FILE = name
changes = _format_changes(old, name)
return _format_state_result(name, result=True, changes=changes) | python | 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
__SYSLOG_NG_CONFIG_FILE = name
changes = _format_changes(old, name)
return _format_state_result(name, result=True, changes=changes) | [
"def",
"set_config_file",
"(",
"name",
")",
":",
"global",
"__SYSLOG_NG_CONFIG_FILE",
"old",
"=",
"__SYSLOG_NG_CONFIG_FILE",
"__SYSLOG_NG_CONFIG_FILE",
"=",
"name",
"changes",
"=",
"_format_changes",
"(",
"old",
",",
"name",
")",
"return",
"_format_state_result",
"(",... | 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 | [
"Sets",
"the",
"configuration",
"s",
"name",
".",
"This",
"function",
"is",
"intended",
"to",
"be",
"used",
"from",
"states",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L705-L721 | train |
saltstack/salt | salt/modules/syslog_ng.py | _run_command | 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) | python | 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",
"_run_command",
"(",
"cmd",
",",
"options",
"=",
"(",
")",
",",
"env",
"=",
"None",
")",
":",
"params",
"=",
"[",
"cmd",
"]",
"params",
".",
"extend",
"(",
"options",
")",
"return",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"params",
",",
... | Runs the command cmd with options as its CLI parameters and returns the
result as a dictionary. | [
"Runs",
"the",
"command",
"cmd",
"with",
"options",
"as",
"its",
"CLI",
"parameters",
"and",
"returns",
"the",
"result",
"as",
"a",
"dictionary",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L738-L745 | train |
saltstack/salt | salt/modules/syslog_ng.py | set_parameters | 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.set_parameters binary_path=/home/user/install/syslog-ng/sbin config_file=/home/user/install/syslog-ng/etc/syslog-ng.conf
'''
if binary_path:
set_binary_path(binary_path)
if config_file:
set_config_file(config_file)
if version:
version = _determine_config_version(__SYSLOG_NG_BINARY_PATH)
write_version(version)
return _format_return_data(0) | python | 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.set_parameters binary_path=/home/user/install/syslog-ng/sbin config_file=/home/user/install/syslog-ng/etc/syslog-ng.conf
'''
if binary_path:
set_binary_path(binary_path)
if config_file:
set_config_file(config_file)
if version:
version = _determine_config_version(__SYSLOG_NG_BINARY_PATH)
write_version(version)
return _format_return_data(0) | [
"def",
"set_parameters",
"(",
"version",
"=",
"None",
",",
"binary_path",
"=",
"None",
",",
"config_file",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"binary_path",
":",
"set_binary_path",
"(",
"binary_path",
")",
"if",
"conf... | 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 | [
"Sets",
"variables",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L761-L785 | train |
saltstack/salt | salt/modules/syslog_ng.py | _run_command_in_extended_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:
# Custom environment variables should be str types. This code
# normalizes the paths to unicode to join them together, and then
# converts back to a str type.
env = {
str('PATH'): salt.utils.stringutils.to_str( # future lint: disable=blacklisted-function
os.pathsep.join(
salt.utils.data.decode(
(orig_path, syslog_ng_sbin_dir)
)
)
)
}
return _run_command(command, options=params, env=env) | python | 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
# normalizes the paths to unicode to join them together, and then
# converts back to a str type.
env = {
str('PATH'): salt.utils.stringutils.to_str( # future lint: disable=blacklisted-function
os.pathsep.join(
salt.utils.data.decode(
(orig_path, syslog_ng_sbin_dir)
)
)
)
}
return _run_command(command, options=params, env=env) | [
"def",
"_run_command_in_extended_path",
"(",
"syslog_ng_sbin_dir",
",",
"command",
",",
"params",
")",
":",
"orig_path",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'PATH'",
",",
"''",
")",
"env",
"=",
"None",
"if",
"syslog_ng_sbin_dir",
":",
"# Custom enviro... | Runs the specified command with the syslog_ng_sbin_dir in the PATH | [
"Runs",
"the",
"specified",
"command",
"with",
"the",
"syslog_ng_sbin_dir",
"in",
"the",
"PATH"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L788-L807 | train |
saltstack/salt | salt/modules/syslog_ng.py | _format_return_data | 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
return ret | python | 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
return ret | [
"def",
"_format_return_data",
"(",
"retcode",
",",
"stdout",
"=",
"None",
",",
"stderr",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'retcode'",
":",
"retcode",
"}",
"if",
"stdout",
"is",
"not",
"None",
":",
"ret",
"[",
"'stdout'",
"]",
"=",
"stdout",
"... | Creates a dictionary from the parameters, which can be used to return data
to Salt. | [
"Creates",
"a",
"dictionary",
"from",
"the",
"parameters",
"which",
"can",
"be",
"used",
"to",
"return",
"data",
"to",
"Salt",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L810-L820 | train |
saltstack/salt | salt/modules/syslog_ng.py | version | 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.version /home/user/install/syslog-ng/sbin
'''
try:
ret = _run_command_in_extended_path(syslog_ng_sbin_dir,
'syslog-ng',
('-V',))
except CommandExecutionError as err:
return _format_return_data(retcode=-1, stderr=six.text_type(err))
if ret['retcode'] != 0:
return _format_return_data(ret['retcode'],
stderr=ret['stderr'],
stdout=ret['stdout'])
lines = ret['stdout'].split('\n')
# The format of the first line in the output is:
# syslog-ng 3.6.0alpha0
version_line_index = 0
version_column_index = 1
line = lines[version_line_index].split()[version_column_index]
return _format_return_data(0, stdout=line) | python | 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.version /home/user/install/syslog-ng/sbin
'''
try:
ret = _run_command_in_extended_path(syslog_ng_sbin_dir,
'syslog-ng',
('-V',))
except CommandExecutionError as err:
return _format_return_data(retcode=-1, stderr=six.text_type(err))
if ret['retcode'] != 0:
return _format_return_data(ret['retcode'],
stderr=ret['stderr'],
stdout=ret['stdout'])
lines = ret['stdout'].split('\n')
# The format of the first line in the output is:
# syslog-ng 3.6.0alpha0
version_line_index = 0
version_column_index = 1
line = lines[version_line_index].split()[version_column_index]
return _format_return_data(0, stdout=line) | [
"def",
"version",
"(",
"syslog_ng_sbin_dir",
"=",
"None",
")",
":",
"try",
":",
"ret",
"=",
"_run_command_in_extended_path",
"(",
"syslog_ng_sbin_dir",
",",
"'syslog-ng'",
",",
"(",
"'-V'",
",",
")",
")",
"except",
"CommandExecutionError",
"as",
"err",
":",
"r... | 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 | [
"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",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L853-L884 | train |
saltstack/salt | salt/modules/syslog_ng.py | modules | 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/install/syslog-ng/sbin
'''
try:
ret = _run_command_in_extended_path(syslog_ng_sbin_dir,
'syslog-ng',
('-V',))
except CommandExecutionError as err:
return _format_return_data(retcode=-1, stderr=six.text_type(err))
if ret['retcode'] != 0:
return _format_return_data(ret['retcode'],
ret.get('stdout'),
ret.get('stderr'))
lines = ret['stdout'].split('\n')
for line in lines:
if line.startswith('Available-Modules'):
label, installed_modules = line.split()
return _format_return_data(ret['retcode'],
stdout=installed_modules)
return _format_return_data(-1, stderr='Unable to find the modules.') | python | 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/install/syslog-ng/sbin
'''
try:
ret = _run_command_in_extended_path(syslog_ng_sbin_dir,
'syslog-ng',
('-V',))
except CommandExecutionError as err:
return _format_return_data(retcode=-1, stderr=six.text_type(err))
if ret['retcode'] != 0:
return _format_return_data(ret['retcode'],
ret.get('stdout'),
ret.get('stderr'))
lines = ret['stdout'].split('\n')
for line in lines:
if line.startswith('Available-Modules'):
label, installed_modules = line.split()
return _format_return_data(ret['retcode'],
stdout=installed_modules)
return _format_return_data(-1, stderr='Unable to find the modules.') | [
"def",
"modules",
"(",
"syslog_ng_sbin_dir",
"=",
"None",
")",
":",
"try",
":",
"ret",
"=",
"_run_command_in_extended_path",
"(",
"syslog_ng_sbin_dir",
",",
"'syslog-ng'",
",",
"(",
"'-V'",
",",
")",
")",
"except",
"CommandExecutionError",
"as",
"err",
":",
"r... | 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 | [
"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",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L887-L917 | train |
saltstack/salt | salt/modules/syslog_ng.py | stats | 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 '*' syslog_ng.stats /home/user/install/syslog-ng/sbin
'''
try:
ret = _run_command_in_extended_path(syslog_ng_sbin_dir,
'syslog-ng-ctl',
('stats',))
except CommandExecutionError as err:
return _format_return_data(retcode=-1, stderr=six.text_type(err))
return _format_return_data(ret['retcode'],
ret.get('stdout'),
ret.get('stderr')) | python | 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 '*' syslog_ng.stats /home/user/install/syslog-ng/sbin
'''
try:
ret = _run_command_in_extended_path(syslog_ng_sbin_dir,
'syslog-ng-ctl',
('stats',))
except CommandExecutionError as err:
return _format_return_data(retcode=-1, stderr=six.text_type(err))
return _format_return_data(ret['retcode'],
ret.get('stdout'),
ret.get('stderr')) | [
"def",
"stats",
"(",
"syslog_ng_sbin_dir",
"=",
"None",
")",
":",
"try",
":",
"ret",
"=",
"_run_command_in_extended_path",
"(",
"syslog_ng_sbin_dir",
",",
"'syslog-ng-ctl'",
",",
"(",
"'stats'",
",",
")",
")",
"except",
"CommandExecutionError",
"as",
"err",
":",... | 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 | [
"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",
"-",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L920-L942 | train |
saltstack/salt | salt/modules/syslog_ng.py | _format_state_result | 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} | python | 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",
"_format_state_result",
"(",
"name",
",",
"result",
",",
"changes",
"=",
"None",
",",
"comment",
"=",
"''",
")",
":",
"if",
"changes",
"is",
"None",
":",
"changes",
"=",
"{",
"'old'",
":",
"''",
",",
"'new'",
":",
"''",
"}",
"return",
"{",
"... | Creates the state result dictionary. | [
"Creates",
"the",
"state",
"result",
"dictionary",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L949-L956 | train |
saltstack/salt | salt/modules/syslog_ng.py | _add_cli_param | 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)) | python | 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_cli_param",
"(",
"params",
",",
"key",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"params",
".",
"append",
"(",
"'--{0}={1}'",
".",
"format",
"(",
"key",
",",
"value",
")",
")"
] | Adds key and value as a command line parameter to params. | [
"Adds",
"key",
"and",
"value",
"as",
"a",
"command",
"line",
"parameter",
"to",
"params",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L959-L964 | train |
saltstack/salt | salt/modules/syslog_ng.py | _add_boolean_cli_param | 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)) | python | 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",
"_add_boolean_cli_param",
"(",
"params",
",",
"key",
",",
"value",
")",
":",
"if",
"value",
"is",
"True",
":",
"params",
".",
"append",
"(",
"'--{0}'",
".",
"format",
"(",
"key",
")",
")"
] | Adds key as a command line parameter to params. | [
"Adds",
"key",
"as",
"a",
"command",
"line",
"parameter",
"to",
"params",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L967-L972 | train |
saltstack/salt | salt/modules/syslog_ng.py | stop | 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
will use the set binary path.
CLI Example:
.. code-block:: bash
salt '*' syslog_ng.stop
'''
pids = __salt__['ps.pgrep'](pattern='syslog-ng')
if not pids:
return _format_state_result(name,
result=False,
comment='Syslog-ng is not running')
if __opts__.get('test', False):
comment = 'Syslog_ng state module will kill {0} pids'
return _format_state_result(name, result=None, comment=comment)
res = __salt__['ps.pkill']('syslog-ng')
killed_pids = res['killed']
if killed_pids == pids:
changes = {'old': killed_pids, 'new': []}
return _format_state_result(name, result=True, changes=changes)
else:
return _format_state_result(name, result=False) | python | 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
will use the set binary path.
CLI Example:
.. code-block:: bash
salt '*' syslog_ng.stop
'''
pids = __salt__['ps.pgrep'](pattern='syslog-ng')
if not pids:
return _format_state_result(name,
result=False,
comment='Syslog-ng is not running')
if __opts__.get('test', False):
comment = 'Syslog_ng state module will kill {0} pids'
return _format_state_result(name, result=None, comment=comment)
res = __salt__['ps.pkill']('syslog-ng')
killed_pids = res['killed']
if killed_pids == pids:
changes = {'old': killed_pids, 'new': []}
return _format_state_result(name, result=True, changes=changes)
else:
return _format_state_result(name, result=False) | [
"def",
"stop",
"(",
"name",
"=",
"None",
")",
":",
"pids",
"=",
"__salt__",
"[",
"'ps.pgrep'",
"]",
"(",
"pattern",
"=",
"'syslog-ng'",
")",
"if",
"not",
"pids",
":",
"return",
"_format_state_result",
"(",
"name",
",",
"result",
"=",
"False",
",",
"com... | 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.
CLI Example:
.. code-block:: bash
salt '*' syslog_ng.stop | [
"Kills",
"syslog",
"-",
"ng",
".",
"This",
"function",
"is",
"intended",
"to",
"be",
"used",
"from",
"the",
"state",
"module",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L975-L1009 | train |
saltstack/salt | salt/modules/syslog_ng.py | start | 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,
persist_file=None,
control=None,
worker_threads=None):
'''
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, this function
will use the set binary path.
CLI Example:
.. code-block:: bash
salt '*' syslog_ng.start
'''
params = []
_add_cli_param(params, 'user', user)
_add_cli_param(params, 'group', group)
_add_cli_param(params, 'chroot', chroot)
_add_cli_param(params, 'caps', caps)
_add_boolean_cli_param(params, 'no-capse', no_caps)
_add_cli_param(params, 'pidfile', pidfile)
_add_boolean_cli_param(params, 'enable-core', enable_core)
_add_cli_param(params, 'fd-limit', fd_limit)
_add_boolean_cli_param(params, 'verbose', verbose)
_add_boolean_cli_param(params, 'debug', debug)
_add_boolean_cli_param(params, 'trace', trace)
_add_boolean_cli_param(params, 'yydebug', yydebug)
_add_cli_param(params, 'cfgfile', __SYSLOG_NG_CONFIG_FILE)
_add_boolean_cli_param(params, 'persist-file', persist_file)
_add_cli_param(params, 'control', control)
_add_cli_param(params, 'worker-threads', worker_threads)
if __SYSLOG_NG_BINARY_PATH:
syslog_ng_binary = os.path.join(__SYSLOG_NG_BINARY_PATH, 'syslog-ng')
command = [syslog_ng_binary] + params
if __opts__.get('test', False):
comment = 'Syslog_ng state module will start {0}'.format(command)
return _format_state_result(name, result=None, comment=comment)
result = __salt__['cmd.run_all'](command, python_shell=False)
else:
command = ['syslog-ng'] + params
if __opts__.get('test', False):
comment = 'Syslog_ng state module will start {0}'.format(command)
return _format_state_result(name, result=None, comment=comment)
result = __salt__['cmd.run_all'](command, python_shell=False)
if result['pid'] > 0:
succ = True
else:
succ = False
return _format_state_result(
name, result=succ, changes={'new': ' '.join(command), 'old': ''}
) | python | 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,
persist_file=None,
control=None,
worker_threads=None):
'''
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, this function
will use the set binary path.
CLI Example:
.. code-block:: bash
salt '*' syslog_ng.start
'''
params = []
_add_cli_param(params, 'user', user)
_add_cli_param(params, 'group', group)
_add_cli_param(params, 'chroot', chroot)
_add_cli_param(params, 'caps', caps)
_add_boolean_cli_param(params, 'no-capse', no_caps)
_add_cli_param(params, 'pidfile', pidfile)
_add_boolean_cli_param(params, 'enable-core', enable_core)
_add_cli_param(params, 'fd-limit', fd_limit)
_add_boolean_cli_param(params, 'verbose', verbose)
_add_boolean_cli_param(params, 'debug', debug)
_add_boolean_cli_param(params, 'trace', trace)
_add_boolean_cli_param(params, 'yydebug', yydebug)
_add_cli_param(params, 'cfgfile', __SYSLOG_NG_CONFIG_FILE)
_add_boolean_cli_param(params, 'persist-file', persist_file)
_add_cli_param(params, 'control', control)
_add_cli_param(params, 'worker-threads', worker_threads)
if __SYSLOG_NG_BINARY_PATH:
syslog_ng_binary = os.path.join(__SYSLOG_NG_BINARY_PATH, 'syslog-ng')
command = [syslog_ng_binary] + params
if __opts__.get('test', False):
comment = 'Syslog_ng state module will start {0}'.format(command)
return _format_state_result(name, result=None, comment=comment)
result = __salt__['cmd.run_all'](command, python_shell=False)
else:
command = ['syslog-ng'] + params
if __opts__.get('test', False):
comment = 'Syslog_ng state module will start {0}'.format(command)
return _format_state_result(name, result=None, comment=comment)
result = __salt__['cmd.run_all'](command, python_shell=False)
if result['pid'] > 0:
succ = True
else:
succ = False
return _format_state_result(
name, result=succ, changes={'new': ' '.join(command), 'old': ''}
) | [
"def",
"start",
"(",
"name",
"=",
"None",
",",
"user",
"=",
"None",
",",
"group",
"=",
"None",
",",
"chroot",
"=",
"None",
",",
"caps",
"=",
"None",
",",
"no_caps",
"=",
"False",
",",
"pidfile",
"=",
"None",
",",
"enable_core",
"=",
"False",
",",
... | 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, this function
will use the set binary path.
CLI Example:
.. code-block:: bash
salt '*' syslog_ng.start | [
"Ensures",
"that",
"syslog",
"-",
"ng",
"is",
"started",
"via",
"the",
"given",
"parameters",
".",
"This",
"function",
"is",
"intended",
"to",
"be",
"used",
"from",
"the",
"state",
"module",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L1012-L1086 | train |
saltstack/salt | salt/modules/syslog_ng.py | reload_ | 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 '*' syslog_ng.reload
'''
if __SYSLOG_NG_BINARY_PATH:
syslog_ng_ctl_binary = os.path.join(__SYSLOG_NG_BINARY_PATH,
'syslog-ng-ctl')
command = [syslog_ng_ctl_binary, 'reload']
result = __salt__['cmd.run_all'](command, python_shell=False)
else:
command = ['syslog-ng-ctl', 'reload']
result = __salt__['cmd.run_all'](command, python_shell=False)
succ = True if result['retcode'] == 0 else False
return _format_state_result(name, result=succ, comment=result['stdout']) | python | 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 '*' syslog_ng.reload
'''
if __SYSLOG_NG_BINARY_PATH:
syslog_ng_ctl_binary = os.path.join(__SYSLOG_NG_BINARY_PATH,
'syslog-ng-ctl')
command = [syslog_ng_ctl_binary, 'reload']
result = __salt__['cmd.run_all'](command, python_shell=False)
else:
command = ['syslog-ng-ctl', 'reload']
result = __salt__['cmd.run_all'](command, python_shell=False)
succ = True if result['retcode'] == 0 else False
return _format_state_result(name, result=succ, comment=result['stdout']) | [
"def",
"reload_",
"(",
"name",
")",
":",
"if",
"__SYSLOG_NG_BINARY_PATH",
":",
"syslog_ng_ctl_binary",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__SYSLOG_NG_BINARY_PATH",
",",
"'syslog-ng-ctl'",
")",
"command",
"=",
"[",
"syslog_ng_ctl_binary",
",",
"'reload'",
... | 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 | [
"Reloads",
"syslog",
"-",
"ng",
".",
"This",
"function",
"is",
"intended",
"to",
"be",
"used",
"from",
"states",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L1089-L1114 | train |
saltstack/salt | salt/modules/syslog_ng.py | write_config | 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.
CLI Example:
.. code-block:: bash
salt '*' syslog_ng.write_config config='# comment'
'''
succ = _write_config(config, newlines)
changes = _format_changes(new=config)
return _format_state_result(name='', result=succ, changes=changes) | python | 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.
CLI Example:
.. code-block:: bash
salt '*' syslog_ng.write_config config='# comment'
'''
succ = _write_config(config, newlines)
changes = _format_changes(new=config)
return _format_state_result(name='', result=succ, changes=changes) | [
"def",
"write_config",
"(",
"config",
",",
"newlines",
"=",
"2",
")",
":",
"succ",
"=",
"_write_config",
"(",
"config",
",",
"newlines",
")",
"changes",
"=",
"_format_changes",
"(",
"new",
"=",
"config",
")",
"return",
"_format_state_result",
"(",
"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 '*' syslog_ng.write_config config='# comment' | [
"Writes",
"the",
"given",
"parameter",
"config",
"into",
"the",
"config",
"file",
".",
"This",
"function",
"is",
"intended",
"to",
"be",
"used",
"from",
"states",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L1125-L1143 | train |
saltstack/salt | salt/modules/syslog_ng.py | _write_config | 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(__SYSLOG_NG_CONFIG_FILE, 'a') as fha:
fha.write(salt.utils.stringutils.to_str(text))
for _ in range(0, newlines):
fha.write(salt.utils.stringutils.to_str(os.linesep))
return True
except Exception as err:
log.error(six.text_type(err))
return False | python | 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(__SYSLOG_NG_CONFIG_FILE, 'a') as fha:
fha.write(salt.utils.stringutils.to_str(text))
for _ in range(0, newlines):
fha.write(salt.utils.stringutils.to_str(os.linesep))
return True
except Exception as err:
log.error(six.text_type(err))
return False | [
"def",
"_write_config",
"(",
"config",
",",
"newlines",
"=",
"2",
")",
":",
"text",
"=",
"config",
"if",
"isinstance",
"(",
"config",
",",
"dict",
")",
"and",
"len",
"(",
"list",
"(",
"list",
"(",
"config",
".",
"keys",
"(",
")",
")",
")",
")",
"... | Writes the given parameter config into the config file. | [
"Writes",
"the",
"given",
"parameter",
"config",
"into",
"the",
"config",
"file",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L1146-L1164 | train |
saltstack/salt | salt/modules/syslog_ng.py | write_version | 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 config file.
CLI Example:
.. code-block:: bash
salt '*' syslog_ng.write_version name="3.6"
'''
line = '@version: {0}'.format(name)
try:
if os.path.exists(__SYSLOG_NG_CONFIG_FILE):
log.debug(
'Removing previous configuration file: %s',
__SYSLOG_NG_CONFIG_FILE
)
os.remove(__SYSLOG_NG_CONFIG_FILE)
log.debug('Configuration file successfully removed')
header = _format_generated_config_header()
_write_config(config=header, newlines=1)
_write_config(config=line, newlines=2)
return _format_state_result(name, result=True)
except OSError as err:
log.error(
'Failed to remove previous configuration file \'%s\': %s',
__SYSLOG_NG_CONFIG_FILE, err
)
return _format_state_result(name, result=False) | python | 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 config file.
CLI Example:
.. code-block:: bash
salt '*' syslog_ng.write_version name="3.6"
'''
line = '@version: {0}'.format(name)
try:
if os.path.exists(__SYSLOG_NG_CONFIG_FILE):
log.debug(
'Removing previous configuration file: %s',
__SYSLOG_NG_CONFIG_FILE
)
os.remove(__SYSLOG_NG_CONFIG_FILE)
log.debug('Configuration file successfully removed')
header = _format_generated_config_header()
_write_config(config=header, newlines=1)
_write_config(config=line, newlines=2)
return _format_state_result(name, result=True)
except OSError as err:
log.error(
'Failed to remove previous configuration file \'%s\': %s',
__SYSLOG_NG_CONFIG_FILE, err
)
return _format_state_result(name, result=False) | [
"def",
"write_version",
"(",
"name",
")",
":",
"line",
"=",
"'@version: {0}'",
".",
"format",
"(",
"name",
")",
"try",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"__SYSLOG_NG_CONFIG_FILE",
")",
":",
"log",
".",
"debug",
"(",
"'Removing previous conf... | 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:
.. code-block:: bash
salt '*' syslog_ng.write_version name="3.6" | [
"Removes",
"the",
"previous",
"configuration",
"file",
"then",
"creates",
"a",
"new",
"one",
"and",
"writes",
"the",
"name",
"line",
".",
"This",
"function",
"is",
"intended",
"to",
"be",
"used",
"from",
"states",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L1167-L1203 | train |
saltstack/salt | salt/modules/syslog_ng.py | Buildable.build_body | 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.join(body_array) + nl
else:
body = ''
_decrease_indent()
return body | python | 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.join(body_array) + nl
else:
body = ''
_decrease_indent()
return body | [
"def",
"build_body",
"(",
"self",
")",
":",
"_increase_indent",
"(",
")",
"body_array",
"=",
"[",
"x",
".",
"build",
"(",
")",
"for",
"x",
"in",
"self",
".",
"iterable",
"]",
"nl",
"=",
"'\\n'",
"if",
"self",
".",
"append_extra_newline",
"else",
"''",
... | Builds the body of a syslog-ng configuration object. | [
"Builds",
"the",
"body",
"of",
"a",
"syslog",
"-",
"ng",
"configuration",
"object",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L130-L145 | train |
saltstack/salt | salt/modules/syslog_ng.py | Buildable.build | 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 | python | 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",
"build",
"(",
"self",
")",
":",
"header",
"=",
"self",
".",
"build_header",
"(",
")",
"body",
"=",
"self",
".",
"build_body",
"(",
")",
"tail",
"=",
"self",
".",
"build_tail",
"(",
")",
"return",
"header",
"+",
"body",
"+",
"tail"
] | Builds the textual representation of the whole configuration object
with it's children. | [
"Builds",
"the",
"textual",
"representation",
"of",
"the",
"whole",
"configuration",
"object",
"with",
"it",
"s",
"children",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/syslog_ng.py#L147-L155 | train |
saltstack/salt | salt/modules/localemod.py | _parse_dbus_locale | 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_locale = properties.Get('org.freedesktop.locale1', 'Locale')
ret = {}
for env_var in system_locale:
env_var = six.text_type(env_var)
match = re.match(r'^([A-Z_]+)=(.*)$', env_var)
if match:
ret[match.group(1)] = match.group(2).replace('"', '')
else:
log.error('Odd locale parameter "%s" detected in dbus locale '
'output. This should not happen. You should '
'probably investigate what caused this.', env_var)
return ret | python | 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_locale = properties.Get('org.freedesktop.locale1', 'Locale')
ret = {}
for env_var in system_locale:
env_var = six.text_type(env_var)
match = re.match(r'^([A-Z_]+)=(.*)$', env_var)
if match:
ret[match.group(1)] = match.group(2).replace('"', '')
else:
log.error('Odd locale parameter "%s" detected in dbus locale '
'output. This should not happen. You should '
'probably investigate what caused this.', env_var)
return ret | [
"def",
"_parse_dbus_locale",
"(",
")",
":",
"bus",
"=",
"dbus",
".",
"SystemBus",
"(",
")",
"localed",
"=",
"bus",
".",
"get_object",
"(",
"'org.freedesktop.locale1'",
",",
"'/org/freedesktop/locale1'",
")",
"properties",
"=",
"dbus",
".",
"Interface",
"(",
"l... | Get the 'System Locale' parameters from dbus | [
"Get",
"the",
"System",
"Locale",
"parameters",
"from",
"dbus"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/localemod.py#L41-L62 | train |
saltstack/salt | salt/modules/localemod.py | _localectl_status | 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 = None
for line in locale_ctl_out.splitlines():
if ': ' in line: # Keys are separate with ":" and a space (!).
ctl_key, ctl_data = line.split(': ')
ctl_key = ctl_key.strip().lower().replace(' ', '_')
else:
ctl_data = line.strip()
if not ctl_data:
continue
if ctl_key:
if '=' in ctl_data:
loc_set = ctl_data.split('=')
if len(loc_set) == 2:
if ctl_key not in ret:
ret[ctl_key] = {}
ret[ctl_key][loc_set[0]] = loc_set[1]
else:
ret[ctl_key] = {'data': None if ctl_data == 'n/a' else ctl_data}
if not ret:
log.debug("Unable to find any locale information inside the following data:\n%s", locale_ctl_out)
raise CommandExecutionError('Unable to parse result of "localectl"')
return ret | python | 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 = None
for line in locale_ctl_out.splitlines():
if ': ' in line: # Keys are separate with ":" and a space (!).
ctl_key, ctl_data = line.split(': ')
ctl_key = ctl_key.strip().lower().replace(' ', '_')
else:
ctl_data = line.strip()
if not ctl_data:
continue
if ctl_key:
if '=' in ctl_data:
loc_set = ctl_data.split('=')
if len(loc_set) == 2:
if ctl_key not in ret:
ret[ctl_key] = {}
ret[ctl_key][loc_set[0]] = loc_set[1]
else:
ret[ctl_key] = {'data': None if ctl_data == 'n/a' else ctl_data}
if not ret:
log.debug("Unable to find any locale information inside the following data:\n%s", locale_ctl_out)
raise CommandExecutionError('Unable to parse result of "localectl"')
return ret | [
"def",
"_localectl_status",
"(",
")",
":",
"if",
"salt",
".",
"utils",
".",
"path",
".",
"which",
"(",
"'localectl'",
")",
"is",
"None",
":",
"raise",
"CommandExecutionError",
"(",
"'Unable to find \"localectl\"'",
")",
"ret",
"=",
"{",
"}",
"locale_ctl_out",
... | Parse localectl status into a dict.
:return: dict | [
"Parse",
"localectl",
"status",
"into",
"a",
"dict",
".",
":",
"return",
":",
"dict"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/localemod.py#L65-L97 | train |
saltstack/salt | salt/modules/localemod.py | _localectl_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.
'''
locale_params = _parse_dbus_locale() if dbus is not None else _localectl_status().get('system_locale', {})
locale_params['LANG'] = six.text_type(locale)
args = ' '.join(['{0}="{1}"'.format(k, v) for k, v in six.iteritems(locale_params) if v is not None])
return not __salt__['cmd.retcode']('localectl set-locale {0}'.format(args), python_shell=False) | python | 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'] = six.text_type(locale)
args = ' '.join(['{0}="{1}"'.format(k, v) for k, v in six.iteritems(locale_params) if v is not None])
return not __salt__['cmd.retcode']('localectl set-locale {0}'.format(args), python_shell=False) | [
"def",
"_localectl_set",
"(",
"locale",
"=",
"''",
")",
":",
"locale_params",
"=",
"_parse_dbus_locale",
"(",
")",
"if",
"dbus",
"is",
"not",
"None",
"else",
"_localectl_status",
"(",
")",
".",
"get",
"(",
"'system_locale'",
",",
"{",
"}",
")",
"locale_par... | Use systemd's localectl command to set the LANG locale parameter, making
sure not to trample on other params that have been set. | [
"Use",
"systemd",
"s",
"localectl",
"command",
"to",
"set",
"the",
"LANG",
"locale",
"parameter",
"making",
"sure",
"not",
"to",
"trample",
"on",
"other",
"params",
"that",
"have",
"been",
"set",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/localemod.py#L100-L108 | train |
saltstack/salt | salt/modules/localemod.py | 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__)
# localectl on SLE12 is installed but the integration is still broken in latest SP3 due to
# config is rewritten by by many %post installation hooks in the older packages.
# If you use it -- you will break your config. This is not the case in SLE15 anymore.
if lc_ctl and not (__grains__['os_family'] in ['Suse'] and __grains__['osmajorrelease'] in [12]):
ret = (_parse_dbus_locale() if dbus is not None else _localectl_status()['system_locale']).get('LANG', '')
else:
if 'Suse' in __grains__['os_family']:
cmd = 'grep "^RC_LANG" /etc/sysconfig/language'
elif 'RedHat' in __grains__['os_family']:
cmd = 'grep "^LANG=" /etc/sysconfig/i18n'
elif 'Debian' in __grains__['os_family']:
# this block only applies to Debian without systemd
cmd = 'grep "^LANG=" /etc/default/locale'
elif 'Gentoo' in __grains__['os_family']:
cmd = 'eselect --brief locale show'
return __salt__['cmd.run'](cmd).strip()
elif 'Solaris' in __grains__['os_family']:
cmd = 'grep "^LANG=" /etc/default/init'
else: # don't waste time on a failing cmd.run
raise CommandExecutionError('Error: "{0}" is unsupported!'.format(__grains__['oscodename']))
if cmd:
try:
ret = __salt__['cmd.run'](cmd).split('=')[1].replace('"', '')
except IndexError as err:
log.error('Error occurred while running "%s": %s', cmd, err)
return ret | python | 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 is rewritten by by many %post installation hooks in the older packages.
# If you use it -- you will break your config. This is not the case in SLE15 anymore.
if lc_ctl and not (__grains__['os_family'] in ['Suse'] and __grains__['osmajorrelease'] in [12]):
ret = (_parse_dbus_locale() if dbus is not None else _localectl_status()['system_locale']).get('LANG', '')
else:
if 'Suse' in __grains__['os_family']:
cmd = 'grep "^RC_LANG" /etc/sysconfig/language'
elif 'RedHat' in __grains__['os_family']:
cmd = 'grep "^LANG=" /etc/sysconfig/i18n'
elif 'Debian' in __grains__['os_family']:
# this block only applies to Debian without systemd
cmd = 'grep "^LANG=" /etc/default/locale'
elif 'Gentoo' in __grains__['os_family']:
cmd = 'eselect --brief locale show'
return __salt__['cmd.run'](cmd).strip()
elif 'Solaris' in __grains__['os_family']:
cmd = 'grep "^LANG=" /etc/default/init'
else: # don't waste time on a failing cmd.run
raise CommandExecutionError('Error: "{0}" is unsupported!'.format(__grains__['oscodename']))
if cmd:
try:
ret = __salt__['cmd.run'](cmd).split('=')[1].replace('"', '')
except IndexError as err:
log.error('Error occurred while running "%s": %s', cmd, err)
return ret | [
"def",
"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 is rewritten by by many... | Get the current system locale
CLI Example:
.. code-block:: bash
salt '*' locale.get_locale | [
"Get",
"the",
"current",
"system",
"locale"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/localemod.py#L124-L163 | train |
saltstack/salt | salt/modules/localemod.py | set_locale | 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
if lc_ctl and not (__grains__['os_family'] in ['Suse'] and __grains__['osmajorrelease'] in [12]):
return _localectl_set(locale)
if 'Suse' in __grains__['os_family']:
# this block applies to all SUSE systems - also with systemd
if not __salt__['file.file_exists']('/etc/sysconfig/language'):
__salt__['file.touch']('/etc/sysconfig/language')
__salt__['file.replace'](
'/etc/sysconfig/language',
'^RC_LANG=.*',
'RC_LANG="{0}"'.format(locale),
append_if_not_found=True
)
elif 'RedHat' in __grains__['os_family']:
if not __salt__['file.file_exists']('/etc/sysconfig/i18n'):
__salt__['file.touch']('/etc/sysconfig/i18n')
__salt__['file.replace'](
'/etc/sysconfig/i18n',
'^LANG=.*',
'LANG="{0}"'.format(locale),
append_if_not_found=True
)
elif 'Debian' in __grains__['os_family']:
# this block only applies to Debian without systemd
update_locale = salt.utils.path.which('update-locale')
if update_locale is None:
raise CommandExecutionError(
'Cannot set locale: "update-locale" was not found.')
__salt__['cmd.run'](update_locale) # (re)generate /etc/default/locale
__salt__['file.replace'](
'/etc/default/locale',
'^LANG=.*',
'LANG="{0}"'.format(locale),
append_if_not_found=True
)
elif 'Gentoo' in __grains__['os_family']:
cmd = 'eselect --brief locale set {0}'.format(locale)
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0
elif 'Solaris' in __grains__['os_family']:
if locale not in __salt__['locale.list_avail']():
return False
__salt__['file.replace'](
'/etc/default/init',
'^LANG=.*',
'LANG="{0}"'.format(locale),
append_if_not_found=True
)
else:
raise CommandExecutionError('Error: Unsupported platform!')
return True | python | 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
if lc_ctl and not (__grains__['os_family'] in ['Suse'] and __grains__['osmajorrelease'] in [12]):
return _localectl_set(locale)
if 'Suse' in __grains__['os_family']:
# this block applies to all SUSE systems - also with systemd
if not __salt__['file.file_exists']('/etc/sysconfig/language'):
__salt__['file.touch']('/etc/sysconfig/language')
__salt__['file.replace'](
'/etc/sysconfig/language',
'^RC_LANG=.*',
'RC_LANG="{0}"'.format(locale),
append_if_not_found=True
)
elif 'RedHat' in __grains__['os_family']:
if not __salt__['file.file_exists']('/etc/sysconfig/i18n'):
__salt__['file.touch']('/etc/sysconfig/i18n')
__salt__['file.replace'](
'/etc/sysconfig/i18n',
'^LANG=.*',
'LANG="{0}"'.format(locale),
append_if_not_found=True
)
elif 'Debian' in __grains__['os_family']:
# this block only applies to Debian without systemd
update_locale = salt.utils.path.which('update-locale')
if update_locale is None:
raise CommandExecutionError(
'Cannot set locale: "update-locale" was not found.')
__salt__['cmd.run'](update_locale) # (re)generate /etc/default/locale
__salt__['file.replace'](
'/etc/default/locale',
'^LANG=.*',
'LANG="{0}"'.format(locale),
append_if_not_found=True
)
elif 'Gentoo' in __grains__['os_family']:
cmd = 'eselect --brief locale set {0}'.format(locale)
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0
elif 'Solaris' in __grains__['os_family']:
if locale not in __salt__['locale.list_avail']():
return False
__salt__['file.replace'](
'/etc/default/init',
'^LANG=.*',
'LANG="{0}"'.format(locale),
append_if_not_found=True
)
else:
raise CommandExecutionError('Error: Unsupported platform!')
return True | [
"def",
"set_locale",
"(",
"locale",
")",
":",
"lc_ctl",
"=",
"salt",
".",
"utils",
".",
"systemd",
".",
"booted",
"(",
"__context__",
")",
"# localectl on SLE12 is installed but the integration is broken -- config is rewritten by YaST2",
"if",
"lc_ctl",
"and",
"not",
"(... | Sets the current system locale
CLI Example:
.. code-block:: bash
salt '*' locale.set_locale 'en_US.UTF-8' | [
"Sets",
"the",
"current",
"system",
"locale"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/localemod.py#L166-L228 | train |
saltstack/salt | salt/modules/localemod.py | avail | 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('Unable to validate locale "%s"', locale)
return False
avail_locales = __salt__['locale.list_avail']()
locale_exists = next((True for x in avail_locales
if salt.utils.locales.normalize_locale(x.strip()) == normalized_locale), False)
return locale_exists | python | 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('Unable to validate locale "%s"', locale)
return False
avail_locales = __salt__['locale.list_avail']()
locale_exists = next((True for x in avail_locales
if salt.utils.locales.normalize_locale(x.strip()) == normalized_locale), False)
return locale_exists | [
"def",
"avail",
"(",
"locale",
")",
":",
"try",
":",
"normalized_locale",
"=",
"salt",
".",
"utils",
".",
"locales",
".",
"normalize_locale",
"(",
"locale",
")",
"except",
"IndexError",
":",
"log",
".",
"error",
"(",
"'Unable to validate locale \"%s\"'",
",",
... | Check if a locale is available.
.. versionadded:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' locale.avail 'en_US.UTF-8' | [
"Check",
"if",
"a",
"locale",
"is",
"available",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/localemod.py#L231-L251 | train |
saltstack/salt | salt/modules/localemod.py | gen_locale | 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 locale
when generating it.
verbose
Show extra warnings about errors that are normally ignored.
CLI Example:
.. code-block:: bash
salt '*' locale.gen_locale en_US.UTF-8
salt '*' locale.gen_locale 'en_IE.UTF-8 UTF-8' # Debian/Gentoo only
'''
on_debian = __grains__.get('os') == 'Debian'
on_ubuntu = __grains__.get('os') == 'Ubuntu'
on_gentoo = __grains__.get('os_family') == 'Gentoo'
on_suse = __grains__.get('os_family') == 'Suse'
on_solaris = __grains__.get('os_family') == 'Solaris'
if on_solaris: # all locales are pre-generated
return locale in __salt__['locale.list_avail']()
locale_info = salt.utils.locales.split_locale(locale)
locale_search_str = '{0}_{1}'.format(locale_info['language'], locale_info['territory'])
# if the charmap has not been supplied, normalize by appening it
if not locale_info['charmap'] and not on_ubuntu:
locale_info['charmap'] = locale_info['codeset']
locale = salt.utils.locales.join_locale(locale_info)
if on_debian or on_gentoo: # file-based search
search = '/usr/share/i18n/SUPPORTED'
valid = __salt__['file.search'](search,
'^{0}$'.format(locale),
flags=re.MULTILINE)
else: # directory-based search
if on_suse:
search = '/usr/share/locale'
else:
search = '/usr/share/i18n/locales'
try:
valid = locale_search_str in os.listdir(search)
except OSError as ex:
log.error(ex)
raise CommandExecutionError(
"Locale \"{0}\" is not available.".format(locale))
if not valid:
log.error(
'The provided locale "%s" is not found in %s', locale, search)
return False
if os.path.exists('/etc/locale.gen'):
__salt__['file.replace'](
'/etc/locale.gen',
r'^\s*#\s*{0}\s*$'.format(locale),
'{0}\n'.format(locale),
append_if_not_found=True
)
elif on_ubuntu:
__salt__['file.touch'](
'/var/lib/locales/supported.d/{0}'.format(locale_info['language'])
)
__salt__['file.replace'](
'/var/lib/locales/supported.d/{0}'.format(locale_info['language']),
locale,
locale,
append_if_not_found=True
)
if salt.utils.path.which('locale-gen'):
cmd = ['locale-gen']
if on_gentoo:
cmd.append('--generate')
if on_ubuntu:
cmd.append(salt.utils.locales.normalize_locale(locale))
else:
cmd.append(locale)
elif salt.utils.path.which('localedef'):
cmd = ['localedef', '--force', '-i', locale_search_str, '-f', locale_info['codeset'],
'{0}.{1}'.format(locale_search_str,
locale_info['codeset']),
kwargs.get('verbose', False) and '--verbose' or '--quiet']
else:
raise CommandExecutionError(
'Command "locale-gen" or "localedef" was not found on this system.')
res = __salt__['cmd.run_all'](cmd)
if res['retcode']:
log.error(res['stderr'])
if kwargs.get('verbose'):
return res
else:
return res['retcode'] == 0 | python | 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 locale
when generating it.
verbose
Show extra warnings about errors that are normally ignored.
CLI Example:
.. code-block:: bash
salt '*' locale.gen_locale en_US.UTF-8
salt '*' locale.gen_locale 'en_IE.UTF-8 UTF-8' # Debian/Gentoo only
'''
on_debian = __grains__.get('os') == 'Debian'
on_ubuntu = __grains__.get('os') == 'Ubuntu'
on_gentoo = __grains__.get('os_family') == 'Gentoo'
on_suse = __grains__.get('os_family') == 'Suse'
on_solaris = __grains__.get('os_family') == 'Solaris'
if on_solaris: # all locales are pre-generated
return locale in __salt__['locale.list_avail']()
locale_info = salt.utils.locales.split_locale(locale)
locale_search_str = '{0}_{1}'.format(locale_info['language'], locale_info['territory'])
# if the charmap has not been supplied, normalize by appening it
if not locale_info['charmap'] and not on_ubuntu:
locale_info['charmap'] = locale_info['codeset']
locale = salt.utils.locales.join_locale(locale_info)
if on_debian or on_gentoo: # file-based search
search = '/usr/share/i18n/SUPPORTED'
valid = __salt__['file.search'](search,
'^{0}$'.format(locale),
flags=re.MULTILINE)
else: # directory-based search
if on_suse:
search = '/usr/share/locale'
else:
search = '/usr/share/i18n/locales'
try:
valid = locale_search_str in os.listdir(search)
except OSError as ex:
log.error(ex)
raise CommandExecutionError(
"Locale \"{0}\" is not available.".format(locale))
if not valid:
log.error(
'The provided locale "%s" is not found in %s', locale, search)
return False
if os.path.exists('/etc/locale.gen'):
__salt__['file.replace'](
'/etc/locale.gen',
r'^\s*#\s*{0}\s*$'.format(locale),
'{0}\n'.format(locale),
append_if_not_found=True
)
elif on_ubuntu:
__salt__['file.touch'](
'/var/lib/locales/supported.d/{0}'.format(locale_info['language'])
)
__salt__['file.replace'](
'/var/lib/locales/supported.d/{0}'.format(locale_info['language']),
locale,
locale,
append_if_not_found=True
)
if salt.utils.path.which('locale-gen'):
cmd = ['locale-gen']
if on_gentoo:
cmd.append('--generate')
if on_ubuntu:
cmd.append(salt.utils.locales.normalize_locale(locale))
else:
cmd.append(locale)
elif salt.utils.path.which('localedef'):
cmd = ['localedef', '--force', '-i', locale_search_str, '-f', locale_info['codeset'],
'{0}.{1}'.format(locale_search_str,
locale_info['codeset']),
kwargs.get('verbose', False) and '--verbose' or '--quiet']
else:
raise CommandExecutionError(
'Command "locale-gen" or "localedef" was not found on this system.')
res = __salt__['cmd.run_all'](cmd)
if res['retcode']:
log.error(res['stderr'])
if kwargs.get('verbose'):
return res
else:
return res['retcode'] == 0 | [
"def",
"gen_locale",
"(",
"locale",
",",
"*",
"*",
"kwargs",
")",
":",
"on_debian",
"=",
"__grains__",
".",
"get",
"(",
"'os'",
")",
"==",
"'Debian'",
"on_ubuntu",
"=",
"__grains__",
".",
"get",
"(",
"'os'",
")",
"==",
"'Ubuntu'",
"on_gentoo",
"=",
"__... | 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
Show extra warnings about errors that are normally ignored.
CLI Example:
.. code-block:: bash
salt '*' locale.gen_locale en_US.UTF-8
salt '*' locale.gen_locale 'en_IE.UTF-8 UTF-8' # Debian/Gentoo only | [
"Generate",
"a",
"locale",
".",
"Options",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/localemod.py#L254-L357 | train |
saltstack/salt | salt/states/heat.py | _parse_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 exc:
raise ValueError(six.text_type(exc))
else:
if tpl is None:
tpl = {}
if not ('HeatTemplateFormatVersion' in tpl
or 'heat_template_version' in tpl
or 'AWSTemplateFormatVersion' in tpl):
raise ValueError(('Template format version not found.'))
return tpl | python | 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:
raise ValueError(six.text_type(exc))
else:
if tpl is None:
tpl = {}
if not ('HeatTemplateFormatVersion' in tpl
or 'heat_template_version' in tpl
or 'AWSTemplateFormatVersion' in tpl):
raise ValueError(('Template format version not found.'))
return tpl | [
"def",
"_parse_template",
"(",
"tmpl_str",
")",
":",
"tmpl_str",
"=",
"tmpl_str",
".",
"strip",
"(",
")",
"if",
"tmpl_str",
".",
"startswith",
"(",
"'{'",
")",
":",
"tpl",
"=",
"salt",
".",
"utils",
".",
"json",
".",
"loads",
"(",
"tmpl_str",
")",
"e... | Parsing template | [
"Parsing",
"template"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/heat.py#L80-L99 | train |
saltstack/salt | salt/states/heat.py | deployed | 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
environment
File of environment
params
Parameter dict used to create the stack
poll
Poll (in sec.) and report events until stack complete
rollback
Enable rollback on create failure
timeout
Stack creation timeout in minutes
profile
Profile to use
.. versionadded:: 2017.7.5,2018.3.1
The spelling mistake in parameter `enviroment` was corrected to `environment`.
The misspelled version is still supported for backward compatibility, but will
be removed in Salt Neon.
'''
if environment is None and 'enviroment' in connection_args:
salt.utils.versions.warn_until('Neon', (
"Please use the 'environment' parameter instead of the misspelled 'enviroment' "
"parameter which will be removed in Salt Neon."
))
environment = connection_args.pop('enviroment')
log.debug('Deployed with (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)',
name, template, environment, params, poll, rollback,
timeout, update, profile, connection_args)
ret = {'name': None,
'comment': '',
'changes': {},
'result': True}
if not name:
ret['result'] = False
ret['comment'] = 'Name ist not valid'
return ret
ret['name'] = name,
existing_stack = __salt__['heat.show_stack'](name, profile=profile)
if existing_stack['result'] and not update:
ret['comment'] = 'Stack {0} is deployed'.format(name)
return ret
if existing_stack['result'] and update:
if template:
template_tmp_file = salt.utils.files.mkstemp()
tsfn, source_sum, comment_ = __salt__['file.get_managed'](
name=template_tmp_file,
template=None,
source=template,
source_hash=None,
user=None,
group=None,
mode=None,
saltenv='base',
context=None,
defaults=None,
skip_verify=False,
kwargs=None)
template_manage_result = __salt__['file.manage_file'](
name=template_tmp_file,
sfn=tsfn,
ret=None,
source=template,
source_sum=source_sum,
user=None,
group=None,
mode=None,
saltenv='base',
backup=None,
makedirs=True,
template=None,
show_changes=False,
contents=None,
dir_mode=None)
if (template_manage_result['result']) or \
((__opts__['test']) and (template_manage_result['result'] is not False)):
with salt.utils.files.fopen(template_tmp_file, 'r') as tfp_:
tpl = salt.utils.stringutils.to_unicode(tfp_.read())
salt.utils.files.safe_rm(template_tmp_file)
try:
template_parse = _parse_template(tpl)
if 'heat_template_version' in template_parse:
template_new = salt.utils.yaml.safe_dump(template_parse)
else:
template_new = jsonutils.dumps(template_parse, indent=2, ensure_ascii=False)
salt.utils.files.safe_rm(template_tmp_file)
except ValueError as ex:
ret['result'] = False
ret['comment'] = 'Error parsing template {0}'.format(ex)
else:
ret['result'] = False
ret['comment'] = 'Can not open template: {0} {1}'.format(template, comment_)
else:
ret['result'] = False
ret['comment'] = 'Can not open template'
if ret['result'] is True:
template_stack = __salt__['heat.template_stack'](name=name, profile=profile)
if not template_stack['result']:
ret['result'] = False
ret['comment'] = template_stack['comment']
if ret['result'] is False:
return ret
try:
checksum_template = __salt__['hashutil.digest'](template_new)
checksum_stack = __salt__['hashutil.digest'](template_stack['template'])
except salt.exceptions.CommandExecutionError as cmdexc:
ret['result'] = False
ret['comment'] = '{0}'.format(cmdexc)
if ret['result'] is True:
if checksum_template == checksum_stack:
if __opts__['test']:
ret['result'] = True
ret['comment'] = 'Stack {0} is deployed'.format(name)
return ret
else:
ret['result'] = False
ret['comment'] = 'Templates have same checksum: {0} {1}'\
.format(checksum_template, checksum_stack)
if ret['result'] is False:
return ret
if __opts__['test']:
stack = {
'result': None,
'comment': 'Stack {0} is set to be updated'.format(name)
}
else:
stack = __salt__['heat.update_stack'](name=name,
template_file=template,
environment=environment,
parameters=params, poll=poll,
rollback=rollback,
timeout=timeout,
profile=profile)
ret['changes']['stack_name'] = name
ret['changes']['comment'] = 'Update stack'
else:
if __opts__['test']:
stack = {
'result': None,
'comment': 'Stack {0} is set to be created'.format(name)
}
else:
stack = __salt__['heat.create_stack'](name=name,
template_file=template,
environment=environment,
parameters=params, poll=poll,
rollback=rollback,
timeout=timeout,
profile=profile)
ret['changes']['stack_name'] = name
ret['changes']['comment'] = 'Create stack'
ret['result'] = stack['result']
ret['comment'] = stack['comment']
return ret | python | 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
environment
File of environment
params
Parameter dict used to create the stack
poll
Poll (in sec.) and report events until stack complete
rollback
Enable rollback on create failure
timeout
Stack creation timeout in minutes
profile
Profile to use
.. versionadded:: 2017.7.5,2018.3.1
The spelling mistake in parameter `enviroment` was corrected to `environment`.
The misspelled version is still supported for backward compatibility, but will
be removed in Salt Neon.
'''
if environment is None and 'enviroment' in connection_args:
salt.utils.versions.warn_until('Neon', (
"Please use the 'environment' parameter instead of the misspelled 'enviroment' "
"parameter which will be removed in Salt Neon."
))
environment = connection_args.pop('enviroment')
log.debug('Deployed with (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)',
name, template, environment, params, poll, rollback,
timeout, update, profile, connection_args)
ret = {'name': None,
'comment': '',
'changes': {},
'result': True}
if not name:
ret['result'] = False
ret['comment'] = 'Name ist not valid'
return ret
ret['name'] = name,
existing_stack = __salt__['heat.show_stack'](name, profile=profile)
if existing_stack['result'] and not update:
ret['comment'] = 'Stack {0} is deployed'.format(name)
return ret
if existing_stack['result'] and update:
if template:
template_tmp_file = salt.utils.files.mkstemp()
tsfn, source_sum, comment_ = __salt__['file.get_managed'](
name=template_tmp_file,
template=None,
source=template,
source_hash=None,
user=None,
group=None,
mode=None,
saltenv='base',
context=None,
defaults=None,
skip_verify=False,
kwargs=None)
template_manage_result = __salt__['file.manage_file'](
name=template_tmp_file,
sfn=tsfn,
ret=None,
source=template,
source_sum=source_sum,
user=None,
group=None,
mode=None,
saltenv='base',
backup=None,
makedirs=True,
template=None,
show_changes=False,
contents=None,
dir_mode=None)
if (template_manage_result['result']) or \
((__opts__['test']) and (template_manage_result['result'] is not False)):
with salt.utils.files.fopen(template_tmp_file, 'r') as tfp_:
tpl = salt.utils.stringutils.to_unicode(tfp_.read())
salt.utils.files.safe_rm(template_tmp_file)
try:
template_parse = _parse_template(tpl)
if 'heat_template_version' in template_parse:
template_new = salt.utils.yaml.safe_dump(template_parse)
else:
template_new = jsonutils.dumps(template_parse, indent=2, ensure_ascii=False)
salt.utils.files.safe_rm(template_tmp_file)
except ValueError as ex:
ret['result'] = False
ret['comment'] = 'Error parsing template {0}'.format(ex)
else:
ret['result'] = False
ret['comment'] = 'Can not open template: {0} {1}'.format(template, comment_)
else:
ret['result'] = False
ret['comment'] = 'Can not open template'
if ret['result'] is True:
template_stack = __salt__['heat.template_stack'](name=name, profile=profile)
if not template_stack['result']:
ret['result'] = False
ret['comment'] = template_stack['comment']
if ret['result'] is False:
return ret
try:
checksum_template = __salt__['hashutil.digest'](template_new)
checksum_stack = __salt__['hashutil.digest'](template_stack['template'])
except salt.exceptions.CommandExecutionError as cmdexc:
ret['result'] = False
ret['comment'] = '{0}'.format(cmdexc)
if ret['result'] is True:
if checksum_template == checksum_stack:
if __opts__['test']:
ret['result'] = True
ret['comment'] = 'Stack {0} is deployed'.format(name)
return ret
else:
ret['result'] = False
ret['comment'] = 'Templates have same checksum: {0} {1}'\
.format(checksum_template, checksum_stack)
if ret['result'] is False:
return ret
if __opts__['test']:
stack = {
'result': None,
'comment': 'Stack {0} is set to be updated'.format(name)
}
else:
stack = __salt__['heat.update_stack'](name=name,
template_file=template,
environment=environment,
parameters=params, poll=poll,
rollback=rollback,
timeout=timeout,
profile=profile)
ret['changes']['stack_name'] = name
ret['changes']['comment'] = 'Update stack'
else:
if __opts__['test']:
stack = {
'result': None,
'comment': 'Stack {0} is set to be created'.format(name)
}
else:
stack = __salt__['heat.create_stack'](name=name,
template_file=template,
environment=environment,
parameters=params, poll=poll,
rollback=rollback,
timeout=timeout,
profile=profile)
ret['changes']['stack_name'] = name
ret['changes']['comment'] = 'Create stack'
ret['result'] = stack['result']
ret['comment'] = stack['comment']
return ret | [
"def",
"deployed",
"(",
"name",
",",
"template",
"=",
"None",
",",
"environment",
"=",
"None",
",",
"params",
"=",
"None",
",",
"poll",
"=",
"5",
",",
"rollback",
"=",
"False",
",",
"timeout",
"=",
"60",
",",
"update",
"=",
"False",
",",
"profile",
... | 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
Enable rollback on create failure
timeout
Stack creation timeout in minutes
profile
Profile to use
.. versionadded:: 2017.7.5,2018.3.1
The spelling mistake in parameter `enviroment` was corrected to `environment`.
The misspelled version is still supported for backward compatibility, but will
be removed in Salt Neon. | [
"Deploy",
"stack",
"with",
"the",
"specified",
"properties"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/heat.py#L102-L281 | train |
saltstack/salt | salt/states/heat.py | absent | 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
'''
log.debug('Absent with (%s, %s %s)', name, poll, profile)
ret = {'name': None,
'comment': '',
'changes': {},
'result': True}
if not name:
ret['result'] = False
ret['comment'] = 'Name ist not valid'
return ret
ret['name'] = name,
existing_stack = __salt__['heat.show_stack'](name, profile=profile)
if not existing_stack['result']:
ret['result'] = True
ret['comment'] = 'Stack not exist'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Stack {0} is set to be removed'.format(name)
return ret
stack = __salt__['heat.delete_stack'](name=name, poll=poll,
timeout=timeout, profile=profile)
ret['result'] = stack['result']
ret['comment'] = stack['comment']
ret['changes']['stack_name'] = name
ret['changes']['comment'] = 'Delete stack'
return ret | python | 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
'''
log.debug('Absent with (%s, %s %s)', name, poll, profile)
ret = {'name': None,
'comment': '',
'changes': {},
'result': True}
if not name:
ret['result'] = False
ret['comment'] = 'Name ist not valid'
return ret
ret['name'] = name,
existing_stack = __salt__['heat.show_stack'](name, profile=profile)
if not existing_stack['result']:
ret['result'] = True
ret['comment'] = 'Stack not exist'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Stack {0} is set to be removed'.format(name)
return ret
stack = __salt__['heat.delete_stack'](name=name, poll=poll,
timeout=timeout, profile=profile)
ret['result'] = stack['result']
ret['comment'] = stack['comment']
ret['changes']['stack_name'] = name
ret['changes']['comment'] = 'Delete stack'
return ret | [
"def",
"absent",
"(",
"name",
",",
"poll",
"=",
"5",
",",
"timeout",
"=",
"60",
",",
"profile",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"'Absent with (%s, %s %s)'",
",",
"name",
",",
"poll",
",",
"profile",
")",
"ret",
"=",
"{",
"'name'",
... | 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 | [
"Ensure",
"that",
"the",
"named",
"stack",
"is",
"absent"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/heat.py#L284-L331 | train |
saltstack/salt | salt/grains/minion_process.py | _username | def _username():
'''
Grain for the minion username
'''
if pwd:
username = pwd.getpwuid(os.getuid()).pw_name
else:
username = getpass.getuser()
return username | python | def _username():
'''
Grain for the minion username
'''
if pwd:
username = pwd.getpwuid(os.getuid()).pw_name
else:
username = getpass.getuser()
return username | [
"def",
"_username",
"(",
")",
":",
"if",
"pwd",
":",
"username",
"=",
"pwd",
".",
"getpwuid",
"(",
"os",
".",
"getuid",
"(",
")",
")",
".",
"pw_name",
"else",
":",
"username",
"=",
"getpass",
".",
"getuser",
"(",
")",
"return",
"username"
] | Grain for the minion username | [
"Grain",
"for",
"the",
"minion",
"username"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/minion_process.py#L34-L43 | train |
saltstack/salt | salt/grains/minion_process.py | _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 | python | 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",
"_groupname",
"(",
")",
":",
"if",
"grp",
":",
"try",
":",
"groupname",
"=",
"grp",
".",
"getgrgid",
"(",
"os",
".",
"getgid",
"(",
")",
")",
".",
"gr_name",
"except",
"KeyError",
":",
"groupname",
"=",
"''",
"else",
":",
"groupname",
"=",
"... | Grain for the minion groupname | [
"Grain",
"for",
"the",
"minion",
"groupname"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/grains/minion_process.py#L55-L67 | train |
saltstack/salt | salt/payload.py | unpackage | def unpackage(package_):
'''
Unpackages a payload
'''
return salt.utils.msgpack.loads(package_, use_list=True,
_msgpack_module=msgpack) | python | def unpackage(package_):
'''
Unpackages a payload
'''
return salt.utils.msgpack.loads(package_, use_list=True,
_msgpack_module=msgpack) | [
"def",
"unpackage",
"(",
"package_",
")",
":",
"return",
"salt",
".",
"utils",
".",
"msgpack",
".",
"loads",
"(",
"package_",
",",
"use_list",
"=",
"True",
",",
"_msgpack_module",
"=",
"msgpack",
")"
] | Unpackages a payload | [
"Unpackages",
"a",
"payload"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/payload.py#L89-L94 | train |
saltstack/salt | salt/payload.py | format_payload | 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
return package(payload) | python | 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
return package(payload) | [
"def",
"format_payload",
"(",
"enc",
",",
"*",
"*",
"kwargs",
")",
":",
"payload",
"=",
"{",
"'enc'",
":",
"enc",
"}",
"load",
"=",
"{",
"}",
"for",
"key",
"in",
"kwargs",
":",
"load",
"[",
"key",
"]",
"=",
"kwargs",
"[",
"key",
"]",
"payload",
... | 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. | [
"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",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/payload.py#L97-L107 | train |
saltstack/salt | salt/payload.py | Serial.loads | 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' type and the
'str' type by decoding contents with 'str' type
to what the encoding was set as. Recommended
encoding is 'utf-8' when using Python 3.
If the msgpack data was not encoded using
"use_bin_type=True", it will try to decode
all 'bytes' and 'str' data (the distinction has
been lost in this case) to what the encoding is
set as. In this case, it will fail if any of
the contents cannot be converted.
'''
try:
def ext_type_decoder(code, data):
if code == 78:
data = salt.utils.stringutils.to_unicode(data)
return datetime.datetime.strptime(data, '%Y%m%dT%H:%M:%S.%f')
return data
gc.disable() # performance optimization for msgpack
if msgpack.version >= (0, 4, 0):
# msgpack only supports 'encoding' starting in 0.4.0.
# Due to this, if we don't need it, don't pass it at all so
# that under Python 2 we can still work with older versions
# of msgpack.
try:
ret = salt.utils.msgpack.loads(msg, use_list=True,
ext_hook=ext_type_decoder,
encoding=encoding,
_msgpack_module=msgpack)
except UnicodeDecodeError:
# msg contains binary data
ret = msgpack.loads(msg, use_list=True, ext_hook=ext_type_decoder)
else:
ret = salt.utils.msgpack.loads(msg, use_list=True,
ext_hook=ext_type_decoder,
_msgpack_module=msgpack)
if six.PY3 and encoding is None and not raw:
ret = salt.transport.frame.decode_embedded_strs(ret)
except Exception as exc:
log.critical(
'Could not deserialize msgpack message. This often happens '
'when trying to read a file not in binary mode. '
'To see message payload, enable debug logging and retry. '
'Exception: %s', exc
)
log.debug('Msgpack deserialization failure on message: %s', msg)
gc.collect()
raise
finally:
gc.enable()
return ret | python | 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' type and the
'str' type by decoding contents with 'str' type
to what the encoding was set as. Recommended
encoding is 'utf-8' when using Python 3.
If the msgpack data was not encoded using
"use_bin_type=True", it will try to decode
all 'bytes' and 'str' data (the distinction has
been lost in this case) to what the encoding is
set as. In this case, it will fail if any of
the contents cannot be converted.
'''
try:
def ext_type_decoder(code, data):
if code == 78:
data = salt.utils.stringutils.to_unicode(data)
return datetime.datetime.strptime(data, '%Y%m%dT%H:%M:%S.%f')
return data
gc.disable() # performance optimization for msgpack
if msgpack.version >= (0, 4, 0):
# msgpack only supports 'encoding' starting in 0.4.0.
# Due to this, if we don't need it, don't pass it at all so
# that under Python 2 we can still work with older versions
# of msgpack.
try:
ret = salt.utils.msgpack.loads(msg, use_list=True,
ext_hook=ext_type_decoder,
encoding=encoding,
_msgpack_module=msgpack)
except UnicodeDecodeError:
# msg contains binary data
ret = msgpack.loads(msg, use_list=True, ext_hook=ext_type_decoder)
else:
ret = salt.utils.msgpack.loads(msg, use_list=True,
ext_hook=ext_type_decoder,
_msgpack_module=msgpack)
if six.PY3 and encoding is None and not raw:
ret = salt.transport.frame.decode_embedded_strs(ret)
except Exception as exc:
log.critical(
'Could not deserialize msgpack message. This often happens '
'when trying to read a file not in binary mode. '
'To see message payload, enable debug logging and retry. '
'Exception: %s', exc
)
log.debug('Msgpack deserialization failure on message: %s', msg)
gc.collect()
raise
finally:
gc.enable()
return ret | [
"def",
"loads",
"(",
"self",
",",
"msg",
",",
"encoding",
"=",
"None",
",",
"raw",
"=",
"False",
")",
":",
"try",
":",
"def",
"ext_type_decoder",
"(",
"code",
",",
"data",
")",
":",
"if",
"code",
"==",
"78",
":",
"data",
"=",
"salt",
".",
"utils"... | 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 with 'str' type
to what the encoding was set as. Recommended
encoding is 'utf-8' when using Python 3.
If the msgpack data was not encoded using
"use_bin_type=True", it will try to decode
all 'bytes' and 'str' data (the distinction has
been lost in this case) to what the encoding is
set as. In this case, it will fail if any of
the contents cannot be converted. | [
"Run",
"the",
"correct",
"loads",
"serialization",
"format"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/payload.py#L123-L179 | train |
saltstack/salt | salt/payload.py | Serial.load | 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) | python | 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",
"load",
"(",
"self",
",",
"fn_",
")",
":",
"data",
"=",
"fn_",
".",
"read",
"(",
")",
"fn_",
".",
"close",
"(",
")",
"if",
"data",
":",
"if",
"six",
".",
"PY3",
":",
"return",
"self",
".",
"loads",
"(",
"data",
",",
"encoding",
"=",
"'... | Run the correct serialization to load a file | [
"Run",
"the",
"correct",
"serialization",
"to",
"load",
"a",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/payload.py#L181-L191 | train |
saltstack/salt | salt/payload.py | Serial.dumps | 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.
Since this changes the wire protocol, this
option should not be used outside of IPC.
'''
def ext_type_encoder(obj):
if isinstance(obj, six.integer_types):
# msgpack can't handle the very long Python longs for jids
# Convert any very long longs to strings
return six.text_type(obj)
elif isinstance(obj, (datetime.datetime, datetime.date)):
# msgpack doesn't support datetime.datetime and datetime.date datatypes.
# So here we have converted these types to custom datatype
# This is msgpack Extended types numbered 78
return msgpack.ExtType(78, salt.utils.stringutils.to_bytes(
obj.strftime('%Y%m%dT%H:%M:%S.%f')))
# The same for immutable types
elif isinstance(obj, immutabletypes.ImmutableDict):
return dict(obj)
elif isinstance(obj, immutabletypes.ImmutableList):
return list(obj)
elif isinstance(obj, (set, immutabletypes.ImmutableSet)):
# msgpack can't handle set so translate it to tuple
return tuple(obj)
elif isinstance(obj, CaseInsensitiveDict):
return dict(obj)
# Nothing known exceptions found. Let msgpack raise it's own.
return obj
try:
if msgpack.version >= (0, 4, 0):
# msgpack only supports 'use_bin_type' starting in 0.4.0.
# Due to this, if we don't need it, don't pass it at all so
# that under Python 2 we can still work with older versions
# of msgpack.
return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,
use_bin_type=use_bin_type,
_msgpack_module=msgpack)
else:
return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,
_msgpack_module=msgpack)
except (OverflowError, msgpack.exceptions.PackValueError):
# msgpack<=0.4.6 don't call ext encoder on very long integers raising the error instead.
# Convert any very long longs to strings and call dumps again.
def verylong_encoder(obj, context):
# Make sure we catch recursion here.
objid = id(obj)
if objid in context:
return '<Recursion on {} with id={}>'.format(type(obj).__name__, id(obj))
context.add(objid)
if isinstance(obj, dict):
for key, value in six.iteritems(obj.copy()):
obj[key] = verylong_encoder(value, context)
return dict(obj)
elif isinstance(obj, (list, tuple)):
obj = list(obj)
for idx, entry in enumerate(obj):
obj[idx] = verylong_encoder(entry, context)
return obj
# A value of an Integer object is limited from -(2^63) upto (2^64)-1 by MessagePack
# spec. Here we care only of JIDs that are positive integers.
if isinstance(obj, six.integer_types) and obj >= pow(2, 64):
return six.text_type(obj)
else:
return obj
msg = verylong_encoder(msg, set())
if msgpack.version >= (0, 4, 0):
return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,
use_bin_type=use_bin_type,
_msgpack_module=msgpack)
else:
return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,
_msgpack_module=msgpack) | python | 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.
Since this changes the wire protocol, this
option should not be used outside of IPC.
'''
def ext_type_encoder(obj):
if isinstance(obj, six.integer_types):
# msgpack can't handle the very long Python longs for jids
# Convert any very long longs to strings
return six.text_type(obj)
elif isinstance(obj, (datetime.datetime, datetime.date)):
# msgpack doesn't support datetime.datetime and datetime.date datatypes.
# So here we have converted these types to custom datatype
# This is msgpack Extended types numbered 78
return msgpack.ExtType(78, salt.utils.stringutils.to_bytes(
obj.strftime('%Y%m%dT%H:%M:%S.%f')))
# The same for immutable types
elif isinstance(obj, immutabletypes.ImmutableDict):
return dict(obj)
elif isinstance(obj, immutabletypes.ImmutableList):
return list(obj)
elif isinstance(obj, (set, immutabletypes.ImmutableSet)):
# msgpack can't handle set so translate it to tuple
return tuple(obj)
elif isinstance(obj, CaseInsensitiveDict):
return dict(obj)
# Nothing known exceptions found. Let msgpack raise it's own.
return obj
try:
if msgpack.version >= (0, 4, 0):
# msgpack only supports 'use_bin_type' starting in 0.4.0.
# Due to this, if we don't need it, don't pass it at all so
# that under Python 2 we can still work with older versions
# of msgpack.
return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,
use_bin_type=use_bin_type,
_msgpack_module=msgpack)
else:
return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,
_msgpack_module=msgpack)
except (OverflowError, msgpack.exceptions.PackValueError):
# msgpack<=0.4.6 don't call ext encoder on very long integers raising the error instead.
# Convert any very long longs to strings and call dumps again.
def verylong_encoder(obj, context):
# Make sure we catch recursion here.
objid = id(obj)
if objid in context:
return '<Recursion on {} with id={}>'.format(type(obj).__name__, id(obj))
context.add(objid)
if isinstance(obj, dict):
for key, value in six.iteritems(obj.copy()):
obj[key] = verylong_encoder(value, context)
return dict(obj)
elif isinstance(obj, (list, tuple)):
obj = list(obj)
for idx, entry in enumerate(obj):
obj[idx] = verylong_encoder(entry, context)
return obj
# A value of an Integer object is limited from -(2^63) upto (2^64)-1 by MessagePack
# spec. Here we care only of JIDs that are positive integers.
if isinstance(obj, six.integer_types) and obj >= pow(2, 64):
return six.text_type(obj)
else:
return obj
msg = verylong_encoder(msg, set())
if msgpack.version >= (0, 4, 0):
return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,
use_bin_type=use_bin_type,
_msgpack_module=msgpack)
else:
return salt.utils.msgpack.dumps(msg, default=ext_type_encoder,
_msgpack_module=msgpack) | [
"def",
"dumps",
"(",
"self",
",",
"msg",
",",
"use_bin_type",
"=",
"False",
")",
":",
"def",
"ext_type_encoder",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"six",
".",
"integer_types",
")",
":",
"# msgpack can't handle the very long Python long... | 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, this
option should not be used outside of IPC. | [
"Run",
"the",
"correct",
"dumps",
"serialization",
"format"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/payload.py#L193-L272 | train |
saltstack/salt | salt/payload.py | Serial.dump | 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
# by using "use_bin_type=True".
fn_.write(self.dumps(msg, use_bin_type=True))
fn_.close() | python | 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
# by using "use_bin_type=True".
fn_.write(self.dumps(msg, use_bin_type=True))
fn_.close() | [
"def",
"dump",
"(",
"self",
",",
"msg",
",",
"fn_",
")",
":",
"if",
"six",
".",
"PY2",
":",
"fn_",
".",
"write",
"(",
"self",
".",
"dumps",
"(",
"msg",
")",
")",
"else",
":",
"# When using Python 3, write files in such a way",
"# that the 'bytes' and 'str' t... | Serialize the correct data into the named file object | [
"Serialize",
"the",
"correct",
"data",
"into",
"the",
"named",
"file",
"object"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/payload.py#L274-L285 | train |
saltstack/salt | salt/payload.py | SREQ.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(
zmq.RECONNECT_IVL_MAX, 5000
)
self._set_tcp_keepalive()
if self.master.startswith('tcp://['):
# Hint PF type if bracket enclosed IPv6 address
if hasattr(zmq, 'IPV6'):
self._socket.setsockopt(zmq.IPV6, 1)
elif hasattr(zmq, 'IPV4ONLY'):
self._socket.setsockopt(zmq.IPV4ONLY, 0)
self._socket.linger = self.linger
if self.id_:
self._socket.setsockopt(zmq.IDENTITY, self.id_)
self._socket.connect(self.master)
return self._socket | python | 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.RECONNECT_IVL_MAX, 5000
)
self._set_tcp_keepalive()
if self.master.startswith('tcp://['):
# Hint PF type if bracket enclosed IPv6 address
if hasattr(zmq, 'IPV6'):
self._socket.setsockopt(zmq.IPV6, 1)
elif hasattr(zmq, 'IPV4ONLY'):
self._socket.setsockopt(zmq.IPV4ONLY, 0)
self._socket.linger = self.linger
if self.id_:
self._socket.setsockopt(zmq.IDENTITY, self.id_)
self._socket.connect(self.master)
return self._socket | [
"def",
"socket",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_socket'",
")",
":",
"# create a new one",
"self",
".",
"_socket",
"=",
"self",
".",
"context",
".",
"socket",
"(",
"zmq",
".",
"REQ",
")",
"if",
"hasattr",
"(",
"zmq... | Lazily create the socket. | [
"Lazily",
"create",
"the",
"socket",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/payload.py#L302-L325 | train |
saltstack/salt | salt/payload.py | SREQ.clear_socket | 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 socket: %s', socket)
self.poller.unregister(socket)
else:
for socket in self.poller.sockets:
log.trace('Unregistering socket: %s', socket)
self.poller.unregister(socket[0])
del self._socket | python | 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 socket: %s', socket)
self.poller.unregister(socket)
else:
for socket in self.poller.sockets:
log.trace('Unregistering socket: %s', socket)
self.poller.unregister(socket[0])
del self._socket | [
"def",
"clear_socket",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_socket'",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"poller",
".",
"sockets",
",",
"dict",
")",
":",
"sockets",
"=",
"list",
"(",
"self",
".",
"poller",
".",
... | delete socket if you have it | [
"delete",
"socket",
"if",
"you",
"have",
"it"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/payload.py#L346-L360 | train |
saltstack/salt | salt/payload.py | SREQ.send | 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.POLLIN)
tried = 0
while True:
polled = self.poller.poll(timeout * 1000)
tried += 1
if polled:
break
if tries > 1:
log.info(
'SaltReqTimeoutError: after %s seconds. (Try %s of %s)',
timeout, tried, tries
)
if tried >= tries:
self.clear_socket()
raise SaltReqTimeoutError(
'SaltReqTimeoutError: after {0} seconds, ran {1} '
'tries'.format(timeout * tried, tried)
)
return self.serial.loads(self.socket.recv()) | python | 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.POLLIN)
tried = 0
while True:
polled = self.poller.poll(timeout * 1000)
tried += 1
if polled:
break
if tries > 1:
log.info(
'SaltReqTimeoutError: after %s seconds. (Try %s of %s)',
timeout, tried, tries
)
if tried >= tries:
self.clear_socket()
raise SaltReqTimeoutError(
'SaltReqTimeoutError: after {0} seconds, ran {1} '
'tries'.format(timeout * tried, tried)
)
return self.serial.loads(self.socket.recv()) | [
"def",
"send",
"(",
"self",
",",
"enc",
",",
"load",
",",
"tries",
"=",
"1",
",",
"timeout",
"=",
"60",
")",
":",
"payload",
"=",
"{",
"'enc'",
":",
"enc",
"}",
"payload",
"[",
"'load'",
"]",
"=",
"load",
"pkg",
"=",
"self",
".",
"serial",
".",... | Takes two arguments, the encryption type and the base payload | [
"Takes",
"two",
"arguments",
"the",
"encryption",
"type",
"and",
"the",
"base",
"payload"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/payload.py#L362-L388 | train |
saltstack/salt | salt/payload.py | SREQ.send_auto | 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) | python | 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) | [
"def",
"send_auto",
"(",
"self",
",",
"payload",
",",
"tries",
"=",
"1",
",",
"timeout",
"=",
"60",
")",
":",
"enc",
"=",
"payload",
".",
"get",
"(",
"'enc'",
",",
"'clear'",
")",
"load",
"=",
"payload",
".",
"get",
"(",
"'load'",
",",
"{",
"}",
... | Detect the encryption type based on the payload | [
"Detect",
"the",
"encryption",
"type",
"based",
"on",
"the",
"payload"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/payload.py#L390-L396 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.