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/modules/azurearm_resource.py | policy_assignments_list_for_resource_group | def policy_assignments_list_for_resource_group(resource_group, **kwargs): # pylint: disable=invalid-name
'''
.. versionadded:: 2019.2.0
List all policy assignments for a resource group.
:param resource_group: The resource group name to list policy assignments within.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_assignments_list_for_resource_group testgroup
'''
result = {}
polconn = __utils__['azurearm.get_client']('policy', **kwargs)
try:
policy_assign = __utils__['azurearm.paged_object_to_list'](
polconn.policy_assignments.list_for_resource_group(
resource_group_name=resource_group,
filter=kwargs.get('filter')
)
)
for assign in policy_assign:
result[assign['name']] = assign
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def policy_assignments_list_for_resource_group(resource_group, **kwargs): # pylint: disable=invalid-name
'''
.. versionadded:: 2019.2.0
List all policy assignments for a resource group.
:param resource_group: The resource group name to list policy assignments within.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_assignments_list_for_resource_group testgroup
'''
result = {}
polconn = __utils__['azurearm.get_client']('policy', **kwargs)
try:
policy_assign = __utils__['azurearm.paged_object_to_list'](
polconn.policy_assignments.list_for_resource_group(
resource_group_name=resource_group,
filter=kwargs.get('filter')
)
)
for assign in policy_assign:
result[assign['name']] = assign
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"policy_assignments_list_for_resource_group",
"(",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=invalid-name",
"result",
"=",
"{",
"}",
"polconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'policy'",
",",
"*",
"*",
... | .. versionadded:: 2019.2.0
List all policy assignments for a resource group.
:param resource_group: The resource group name to list policy assignments within.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_assignments_list_for_resource_group testgroup | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L978-L1009 | train |
saltstack/salt | salt/modules/azurearm_resource.py | policy_assignments_list | def policy_assignments_list(**kwargs):
'''
.. versionadded:: 2019.2.0
List all policy assignments for a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_assignments_list
'''
result = {}
polconn = __utils__['azurearm.get_client']('policy', **kwargs)
try:
policy_assign = __utils__['azurearm.paged_object_to_list'](polconn.policy_assignments.list())
for assign in policy_assign:
result[assign['name']] = assign
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def policy_assignments_list(**kwargs):
'''
.. versionadded:: 2019.2.0
List all policy assignments for a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_assignments_list
'''
result = {}
polconn = __utils__['azurearm.get_client']('policy', **kwargs)
try:
policy_assign = __utils__['azurearm.paged_object_to_list'](polconn.policy_assignments.list())
for assign in policy_assign:
result[assign['name']] = assign
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"policy_assignments_list",
"(",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"{",
"}",
"polconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'policy'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"policy_assign",
"=",
"__utils__",
"[",... | .. versionadded:: 2019.2.0
List all policy assignments for a subscription.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_assignments_list | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L1012-L1036 | train |
saltstack/salt | salt/modules/azurearm_resource.py | policy_definition_create_or_update | def policy_definition_create_or_update(name, policy_rule, **kwargs): # pylint: disable=invalid-name
'''
.. versionadded:: 2019.2.0
Create or update a policy definition.
:param name: The name of the policy definition to create or update.
:param policy_rule: A dictionary defining the
`policy rule <https://docs.microsoft.com/en-us/azure/azure-policy/policy-definition#policy-rule>`_.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_definition_create_or_update testpolicy '{...rule definition..}'
'''
if not isinstance(policy_rule, dict):
result = {'error': 'The policy rule must be a dictionary!'}
return result
polconn = __utils__['azurearm.get_client']('policy', **kwargs)
# Convert OrderedDict to dict
prop_kwargs = {'policy_rule': loads(dumps(policy_rule))}
policy_kwargs = kwargs.copy()
policy_kwargs.update(prop_kwargs)
try:
policy_model = __utils__['azurearm.create_object_model'](
'resource.policy',
'PolicyDefinition',
**policy_kwargs
)
except TypeError as exc:
result = {'error': 'The object model could not be built. ({0})'.format(str(exc))}
return result
try:
policy = polconn.policy_definitions.create_or_update(
policy_definition_name=name,
parameters=policy_model
)
result = policy.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
except SerializationError as exc:
result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))}
return result | python | def policy_definition_create_or_update(name, policy_rule, **kwargs): # pylint: disable=invalid-name
'''
.. versionadded:: 2019.2.0
Create or update a policy definition.
:param name: The name of the policy definition to create or update.
:param policy_rule: A dictionary defining the
`policy rule <https://docs.microsoft.com/en-us/azure/azure-policy/policy-definition#policy-rule>`_.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_definition_create_or_update testpolicy '{...rule definition..}'
'''
if not isinstance(policy_rule, dict):
result = {'error': 'The policy rule must be a dictionary!'}
return result
polconn = __utils__['azurearm.get_client']('policy', **kwargs)
# Convert OrderedDict to dict
prop_kwargs = {'policy_rule': loads(dumps(policy_rule))}
policy_kwargs = kwargs.copy()
policy_kwargs.update(prop_kwargs)
try:
policy_model = __utils__['azurearm.create_object_model'](
'resource.policy',
'PolicyDefinition',
**policy_kwargs
)
except TypeError as exc:
result = {'error': 'The object model could not be built. ({0})'.format(str(exc))}
return result
try:
policy = polconn.policy_definitions.create_or_update(
policy_definition_name=name,
parameters=policy_model
)
result = policy.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
except SerializationError as exc:
result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))}
return result | [
"def",
"policy_definition_create_or_update",
"(",
"name",
",",
"policy_rule",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=invalid-name",
"if",
"not",
"isinstance",
"(",
"policy_rule",
",",
"dict",
")",
":",
"result",
"=",
"{",
"'error'",
":",
"'The pol... | .. versionadded:: 2019.2.0
Create or update a policy definition.
:param name: The name of the policy definition to create or update.
:param policy_rule: A dictionary defining the
`policy rule <https://docs.microsoft.com/en-us/azure/azure-policy/policy-definition#policy-rule>`_.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_definition_create_or_update testpolicy '{...rule definition..}' | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L1039-L1091 | train |
saltstack/salt | salt/modules/azurearm_resource.py | policy_definition_delete | def policy_definition_delete(name, **kwargs):
'''
.. versionadded:: 2019.2.0
Delete a policy definition.
:param name: The name of the policy definition to delete.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_definition_delete testpolicy
'''
result = False
polconn = __utils__['azurearm.get_client']('policy', **kwargs)
try:
# pylint: disable=unused-variable
policy = polconn.policy_definitions.delete(
policy_definition_name=name
)
result = True
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
return result | python | def policy_definition_delete(name, **kwargs):
'''
.. versionadded:: 2019.2.0
Delete a policy definition.
:param name: The name of the policy definition to delete.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_definition_delete testpolicy
'''
result = False
polconn = __utils__['azurearm.get_client']('policy', **kwargs)
try:
# pylint: disable=unused-variable
policy = polconn.policy_definitions.delete(
policy_definition_name=name
)
result = True
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
return result | [
"def",
"policy_definition_delete",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"False",
"polconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'policy'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"# pylint: disable=unused-vari... | .. versionadded:: 2019.2.0
Delete a policy definition.
:param name: The name of the policy definition to delete.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_definition_delete testpolicy | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L1094-L1120 | train |
saltstack/salt | salt/modules/azurearm_resource.py | policy_definition_get | def policy_definition_get(name, **kwargs):
'''
.. versionadded:: 2019.2.0
Get details about a specific policy definition.
:param name: The name of the policy definition to query.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_definition_get testpolicy
'''
polconn = __utils__['azurearm.get_client']('policy', **kwargs)
try:
policy_def = polconn.policy_definitions.get(
policy_definition_name=name
)
result = policy_def.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def policy_definition_get(name, **kwargs):
'''
.. versionadded:: 2019.2.0
Get details about a specific policy definition.
:param name: The name of the policy definition to query.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_definition_get testpolicy
'''
polconn = __utils__['azurearm.get_client']('policy', **kwargs)
try:
policy_def = polconn.policy_definitions.get(
policy_definition_name=name
)
result = policy_def.as_dict()
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"policy_definition_get",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"polconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'policy'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"policy_def",
"=",
"polconn",
".",
"policy_definitions"... | .. versionadded:: 2019.2.0
Get details about a specific policy definition.
:param name: The name of the policy definition to query.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_definition_get testpolicy | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L1123-L1148 | train |
saltstack/salt | salt/modules/azurearm_resource.py | policy_definitions_list | def policy_definitions_list(hide_builtin=False, **kwargs):
'''
.. versionadded:: 2019.2.0
List all policy definitions for a subscription.
:param hide_builtin: Boolean which will filter out BuiltIn policy definitions from the result.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_definitions_list
'''
result = {}
polconn = __utils__['azurearm.get_client']('policy', **kwargs)
try:
policy_defs = __utils__['azurearm.paged_object_to_list'](polconn.policy_definitions.list())
for policy in policy_defs:
if not (hide_builtin and policy['policy_type'] == 'BuiltIn'):
result[policy['name']] = policy
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | python | def policy_definitions_list(hide_builtin=False, **kwargs):
'''
.. versionadded:: 2019.2.0
List all policy definitions for a subscription.
:param hide_builtin: Boolean which will filter out BuiltIn policy definitions from the result.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_definitions_list
'''
result = {}
polconn = __utils__['azurearm.get_client']('policy', **kwargs)
try:
policy_defs = __utils__['azurearm.paged_object_to_list'](polconn.policy_definitions.list())
for policy in policy_defs:
if not (hide_builtin and policy['policy_type'] == 'BuiltIn'):
result[policy['name']] = policy
except CloudError as exc:
__utils__['azurearm.log_cloud_error']('resource', str(exc), **kwargs)
result = {'error': str(exc)}
return result | [
"def",
"policy_definitions_list",
"(",
"hide_builtin",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"{",
"}",
"polconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'policy'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"p... | .. versionadded:: 2019.2.0
List all policy definitions for a subscription.
:param hide_builtin: Boolean which will filter out BuiltIn policy definitions from the result.
CLI Example:
.. code-block:: bash
salt-call azurearm_resource.policy_definitions_list | [
"..",
"versionadded",
"::",
"2019",
".",
"2",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_resource.py#L1151-L1178 | train |
saltstack/salt | salt/cloud/clouds/joyent.py | query_instance | def query_instance(vm_=None, call=None):
'''
Query an instance upon creation from the Joyent API
'''
if isinstance(vm_, six.string_types) and call == 'action':
vm_ = {'name': vm_, 'provider': 'joyent'}
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The query_instance action must be called with -a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'querying instance',
'salt/cloud/{0}/querying'.format(vm_['name']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
def _query_ip_address():
data = show_instance(vm_['name'], call='action')
if not data:
log.error(
'There was an error while querying Joyent. Empty response'
)
# Trigger a failure in the wait for IP function
return False
if isinstance(data, dict) and 'error' in data:
log.warning('There was an error in the query %s', data.get('error'))
# Trigger a failure in the wait for IP function
return False
log.debug('Returned query data: %s', data)
if 'primaryIp' in data[1]:
# Wait for SSH to be fully configured on the remote side
if data[1]['state'] == 'running':
return data[1]['primaryIp']
return None
try:
data = salt.utils.cloud.wait_for_ip(
_query_ip_address,
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
interval_multiplier=config.get_cloud_config_value(
'wait_for_ip_interval_multiplier', vm_, __opts__, default=1),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# destroy(vm_['name'])
pass
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
return data | python | def query_instance(vm_=None, call=None):
'''
Query an instance upon creation from the Joyent API
'''
if isinstance(vm_, six.string_types) and call == 'action':
vm_ = {'name': vm_, 'provider': 'joyent'}
if call == 'function':
# Technically this function may be called other ways too, but it
# definitely cannot be called with --function.
raise SaltCloudSystemExit(
'The query_instance action must be called with -a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'querying instance',
'salt/cloud/{0}/querying'.format(vm_['name']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
def _query_ip_address():
data = show_instance(vm_['name'], call='action')
if not data:
log.error(
'There was an error while querying Joyent. Empty response'
)
# Trigger a failure in the wait for IP function
return False
if isinstance(data, dict) and 'error' in data:
log.warning('There was an error in the query %s', data.get('error'))
# Trigger a failure in the wait for IP function
return False
log.debug('Returned query data: %s', data)
if 'primaryIp' in data[1]:
# Wait for SSH to be fully configured on the remote side
if data[1]['state'] == 'running':
return data[1]['primaryIp']
return None
try:
data = salt.utils.cloud.wait_for_ip(
_query_ip_address,
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
interval_multiplier=config.get_cloud_config_value(
'wait_for_ip_interval_multiplier', vm_, __opts__, default=1),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# destroy(vm_['name'])
pass
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc))
return data | [
"def",
"query_instance",
"(",
"vm_",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"vm_",
",",
"six",
".",
"string_types",
")",
"and",
"call",
"==",
"'action'",
":",
"vm_",
"=",
"{",
"'name'",
":",
"vm_",
",",
"'provider'"... | Query an instance upon creation from the Joyent API | [
"Query",
"an",
"instance",
"upon",
"creation",
"from",
"the",
"Joyent",
"API"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/joyent.py#L172-L235 | train |
saltstack/salt | salt/cloud/clouds/joyent.py | create | def create(vm_):
'''
Create a single VM from a data dict
CLI Example:
.. code-block:: bash
salt-cloud -p profile_name vm_name
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'joyent',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
key_filename = config.get_cloud_config_value(
'private_key', vm_, __opts__, search_global=False, default=None
)
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info(
'Creating Cloud VM %s in %s',
vm_['name'], vm_.get('location', DEFAULT_LOCATION)
)
# added . for fqdn hostnames
salt.utils.cloud.check_name(vm_['name'], 'a-zA-Z0-9-.')
kwargs = {
'name': vm_['name'],
'image': get_image(vm_),
'size': get_size(vm_),
'location': vm_.get('location', DEFAULT_LOCATION)
}
# Let's not assign a default here; only assign a network value if
# one is explicitly configured
if 'networks' in vm_:
kwargs['networks'] = vm_.get('networks')
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={
'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
data = create_node(**kwargs)
if data == {}:
log.error('Error creating %s on JOYENT', vm_['name'])
return False
query_instance(vm_)
data = show_instance(vm_['name'], call='action')
vm_['key_filename'] = key_filename
vm_['ssh_host'] = data[1]['primaryIp']
__utils__['cloud.bootstrap'](vm_, __opts__)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return data[1] | python | def create(vm_):
'''
Create a single VM from a data dict
CLI Example:
.. code-block:: bash
salt-cloud -p profile_name vm_name
'''
try:
# Check for required profile parameters before sending any API calls.
if vm_['profile'] and config.is_profile_configured(__opts__,
__active_provider_name__ or 'joyent',
vm_['profile'],
vm_=vm_) is False:
return False
except AttributeError:
pass
key_filename = config.get_cloud_config_value(
'private_key', vm_, __opts__, search_global=False, default=None
)
__utils__['cloud.fire_event'](
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info(
'Creating Cloud VM %s in %s',
vm_['name'], vm_.get('location', DEFAULT_LOCATION)
)
# added . for fqdn hostnames
salt.utils.cloud.check_name(vm_['name'], 'a-zA-Z0-9-.')
kwargs = {
'name': vm_['name'],
'image': get_image(vm_),
'size': get_size(vm_),
'location': vm_.get('location', DEFAULT_LOCATION)
}
# Let's not assign a default here; only assign a network value if
# one is explicitly configured
if 'networks' in vm_:
kwargs['networks'] = vm_.get('networks')
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args={
'kwargs': __utils__['cloud.filter_event']('requesting', kwargs, list(kwargs)),
},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
data = create_node(**kwargs)
if data == {}:
log.error('Error creating %s on JOYENT', vm_['name'])
return False
query_instance(vm_)
data = show_instance(vm_['name'], call='action')
vm_['key_filename'] = key_filename
vm_['ssh_host'] = data[1]['primaryIp']
__utils__['cloud.bootstrap'](vm_, __opts__)
__utils__['cloud.fire_event'](
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
return data[1] | [
"def",
"create",
"(",
"vm_",
")",
":",
"try",
":",
"# Check for required profile parameters before sending any API calls.",
"if",
"vm_",
"[",
"'profile'",
"]",
"and",
"config",
".",
"is_profile_configured",
"(",
"__opts__",
",",
"__active_provider_name__",
"or",
"'joyen... | Create a single VM from a data dict
CLI Example:
.. code-block:: bash
salt-cloud -p profile_name vm_name | [
"Create",
"a",
"single",
"VM",
"from",
"a",
"data",
"dict"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/joyent.py#L238-L322 | train |
saltstack/salt | salt/cloud/clouds/joyent.py | create_node | def create_node(**kwargs):
'''
convenience function to make the rest api call for node creation.
'''
name = kwargs['name']
size = kwargs['size']
image = kwargs['image']
location = kwargs['location']
networks = kwargs.get('networks')
tag = kwargs.get('tag')
locality = kwargs.get('locality')
metadata = kwargs.get('metadata')
firewall_enabled = kwargs.get('firewall_enabled')
create_data = {
'name': name,
'package': size['name'],
'image': image['name'],
}
if networks is not None:
create_data['networks'] = networks
if locality is not None:
create_data['locality'] = locality
if metadata is not None:
for key, value in six.iteritems(metadata):
create_data['metadata.{0}'.format(key)] = value
if tag is not None:
for key, value in six.iteritems(tag):
create_data['tag.{0}'.format(key)] = value
if firewall_enabled is not None:
create_data['firewall_enabled'] = firewall_enabled
data = salt.utils.json.dumps(create_data)
ret = query(command='my/machines', data=data, method='POST',
location=location)
if ret[0] in VALID_RESPONSE_CODES:
return ret[1]
else:
log.error('Failed to create node %s: %s', name, ret[1])
return {} | python | def create_node(**kwargs):
'''
convenience function to make the rest api call for node creation.
'''
name = kwargs['name']
size = kwargs['size']
image = kwargs['image']
location = kwargs['location']
networks = kwargs.get('networks')
tag = kwargs.get('tag')
locality = kwargs.get('locality')
metadata = kwargs.get('metadata')
firewall_enabled = kwargs.get('firewall_enabled')
create_data = {
'name': name,
'package': size['name'],
'image': image['name'],
}
if networks is not None:
create_data['networks'] = networks
if locality is not None:
create_data['locality'] = locality
if metadata is not None:
for key, value in six.iteritems(metadata):
create_data['metadata.{0}'.format(key)] = value
if tag is not None:
for key, value in six.iteritems(tag):
create_data['tag.{0}'.format(key)] = value
if firewall_enabled is not None:
create_data['firewall_enabled'] = firewall_enabled
data = salt.utils.json.dumps(create_data)
ret = query(command='my/machines', data=data, method='POST',
location=location)
if ret[0] in VALID_RESPONSE_CODES:
return ret[1]
else:
log.error('Failed to create node %s: %s', name, ret[1])
return {} | [
"def",
"create_node",
"(",
"*",
"*",
"kwargs",
")",
":",
"name",
"=",
"kwargs",
"[",
"'name'",
"]",
"size",
"=",
"kwargs",
"[",
"'size'",
"]",
"image",
"=",
"kwargs",
"[",
"'image'",
"]",
"location",
"=",
"kwargs",
"[",
"'location'",
"]",
"networks",
... | convenience function to make the rest api call for node creation. | [
"convenience",
"function",
"to",
"make",
"the",
"rest",
"api",
"call",
"for",
"node",
"creation",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/joyent.py#L325-L370 | train |
saltstack/salt | salt/cloud/clouds/joyent.py | destroy | def destroy(name, call=None):
'''
destroy a machine by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
node = get_node(name)
ret = query(command='my/machines/{0}'.format(node['id']),
location=node['location'], method='DELETE')
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
return ret[0] in VALID_RESPONSE_CODES | python | def destroy(name, call=None):
'''
destroy a machine by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
node = get_node(name)
ret = query(command='my/machines/{0}'.format(node['id']),
location=node['location'], method='DELETE')
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
return ret[0] in VALID_RESPONSE_CODES | [
"def",
"destroy",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The destroy action must be called with -d, --destroy, '",
"'-a or --action.'",
")",
"__utils__",
"[",
"'cloud.fire_event'",
... | destroy a machine by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name | [
"destroy",
"a",
"machine",
"by",
"name"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/joyent.py#L373-L420 | train |
saltstack/salt | salt/cloud/clouds/joyent.py | reboot | def reboot(name, call=None):
'''
reboot a machine by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
node = get_node(name)
ret = take_action(name=name, call=call, method='POST',
command='my/machines/{0}'.format(node['id']),
location=node['location'], data={'action': 'reboot'})
return ret[0] in VALID_RESPONSE_CODES | python | def reboot(name, call=None):
'''
reboot a machine by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
node = get_node(name)
ret = take_action(name=name, call=call, method='POST',
command='my/machines/{0}'.format(node['id']),
location=node['location'], data={'action': 'reboot'})
return ret[0] in VALID_RESPONSE_CODES | [
"def",
"reboot",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"node",
"=",
"get_node",
"(",
"name",
")",
"ret",
"=",
"take_action",
"(",
"name",
"=",
"name",
",",
"call",
"=",
"call",
",",
"method",
"=",
"'POST'",
",",
"command",
"=",
"'my/mach... | reboot a machine by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name | [
"reboot",
"a",
"machine",
"by",
"name",
":",
"param",
"name",
":",
"name",
"given",
"to",
"the",
"machine",
":",
"param",
"call",
":",
"call",
"value",
"in",
"this",
"case",
"is",
"action",
":",
"return",
":",
"true",
"if",
"successful"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/joyent.py#L423-L440 | train |
saltstack/salt | salt/cloud/clouds/joyent.py | take_action | def take_action(name=None, call=None, command=None, data=None, method='GET',
location=DEFAULT_LOCATION):
'''
take action call used by start,stop, reboot
:param name: name given to the machine
:param call: call value in this case is 'action'
:command: api path
:data: any data to be passed to the api, must be in json format
:method: GET,POST,or DELETE
:location: data center to execute the command on
:return: true if successful
'''
caller = inspect.stack()[1][3]
if call != 'action':
raise SaltCloudSystemExit(
'This action must be called with -a or --action.'
)
if data:
data = salt.utils.json.dumps(data)
ret = []
try:
ret = query(command=command, data=data, method=method,
location=location)
log.info('Success %s for node %s', caller, name)
except Exception as exc:
if 'InvalidState' in six.text_type(exc):
ret = [200, {}]
else:
log.error(
'Failed to invoke %s node %s: %s', caller, name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
ret = [100, {}]
return ret | python | def take_action(name=None, call=None, command=None, data=None, method='GET',
location=DEFAULT_LOCATION):
'''
take action call used by start,stop, reboot
:param name: name given to the machine
:param call: call value in this case is 'action'
:command: api path
:data: any data to be passed to the api, must be in json format
:method: GET,POST,or DELETE
:location: data center to execute the command on
:return: true if successful
'''
caller = inspect.stack()[1][3]
if call != 'action':
raise SaltCloudSystemExit(
'This action must be called with -a or --action.'
)
if data:
data = salt.utils.json.dumps(data)
ret = []
try:
ret = query(command=command, data=data, method=method,
location=location)
log.info('Success %s for node %s', caller, name)
except Exception as exc:
if 'InvalidState' in six.text_type(exc):
ret = [200, {}]
else:
log.error(
'Failed to invoke %s node %s: %s', caller, name, exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
ret = [100, {}]
return ret | [
"def",
"take_action",
"(",
"name",
"=",
"None",
",",
"call",
"=",
"None",
",",
"command",
"=",
"None",
",",
"data",
"=",
"None",
",",
"method",
"=",
"'GET'",
",",
"location",
"=",
"DEFAULT_LOCATION",
")",
":",
"caller",
"=",
"inspect",
".",
"stack",
... | take action call used by start,stop, reboot
:param name: name given to the machine
:param call: call value in this case is 'action'
:command: api path
:data: any data to be passed to the api, must be in json format
:method: GET,POST,or DELETE
:location: data center to execute the command on
:return: true if successful | [
"take",
"action",
"call",
"used",
"by",
"start",
"stop",
"reboot",
":",
"param",
"name",
":",
"name",
"given",
"to",
"the",
"machine",
":",
"param",
"call",
":",
"call",
"value",
"in",
"this",
"case",
"is",
"action",
":",
"command",
":",
"api",
"path",... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/joyent.py#L484-L524 | train |
saltstack/salt | salt/cloud/clouds/joyent.py | get_location | def get_location(vm_=None):
'''
Return the joyent data center to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
) | python | def get_location(vm_=None):
'''
Return the joyent data center to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
default=DEFAULT_LOCATION,
search_global=False
)
) | [
"def",
"get_location",
"(",
"vm_",
"=",
"None",
")",
":",
"return",
"__opts__",
".",
"get",
"(",
"'location'",
",",
"config",
".",
"get_cloud_config_value",
"(",
"'location'",
",",
"vm_",
"or",
"get_configured_provider",
"(",
")",
",",
"__opts__",
",",
"defa... | Return the joyent data center to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting | [
"Return",
"the",
"joyent",
"data",
"center",
"to",
"use",
"in",
"this",
"order",
":",
"-",
"CLI",
"parameter",
"-",
"VM",
"parameter",
"-",
"Cloud",
"profile",
"setting"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/joyent.py#L538-L554 | train |
saltstack/salt | salt/cloud/clouds/joyent.py | avail_locations | def avail_locations(call=None):
'''
List all available locations
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
ret = {}
for key in JOYENT_LOCATIONS:
ret[key] = {
'name': key,
'region': JOYENT_LOCATIONS[key]
}
# this can be enabled when the bug in the joyent get data centers call is
# corrected, currently only the European dc (new api) returns the correct
# values
# ret = {}
# rcode, datacenters = query(
# command='my/datacenters', location=DEFAULT_LOCATION, method='GET'
# )
# if rcode in VALID_RESPONSE_CODES and isinstance(datacenters, dict):
# for key in datacenters:
# ret[key] = {
# 'name': key,
# 'url': datacenters[key]
# }
return ret | python | def avail_locations(call=None):
'''
List all available locations
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
ret = {}
for key in JOYENT_LOCATIONS:
ret[key] = {
'name': key,
'region': JOYENT_LOCATIONS[key]
}
# this can be enabled when the bug in the joyent get data centers call is
# corrected, currently only the European dc (new api) returns the correct
# values
# ret = {}
# rcode, datacenters = query(
# command='my/datacenters', location=DEFAULT_LOCATION, method='GET'
# )
# if rcode in VALID_RESPONSE_CODES and isinstance(datacenters, dict):
# for key in datacenters:
# ret[key] = {
# 'name': key,
# 'url': datacenters[key]
# }
return ret | [
"def",
"avail_locations",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The avail_locations function must be called with '",
"'-f or --function, or with the --list-locations option'",
")",
"ret",
"=",
"{",
... | List all available locations | [
"List",
"all",
"available",
"locations"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/joyent.py#L557-L587 | train |
saltstack/salt | salt/cloud/clouds/joyent.py | has_method | def has_method(obj, method_name):
'''
Find if the provided object has a specific method
'''
if method_name in dir(obj):
return True
log.error('Method \'%s\' not yet supported!', method_name)
return False | python | def has_method(obj, method_name):
'''
Find if the provided object has a specific method
'''
if method_name in dir(obj):
return True
log.error('Method \'%s\' not yet supported!', method_name)
return False | [
"def",
"has_method",
"(",
"obj",
",",
"method_name",
")",
":",
"if",
"method_name",
"in",
"dir",
"(",
"obj",
")",
":",
"return",
"True",
"log",
".",
"error",
"(",
"'Method \\'%s\\' not yet supported!'",
",",
"method_name",
")",
"return",
"False"
] | Find if the provided object has a specific method | [
"Find",
"if",
"the",
"provided",
"object",
"has",
"a",
"specific",
"method"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/joyent.py#L590-L598 | train |
saltstack/salt | salt/cloud/clouds/joyent.py | key_list | def key_list(items=None):
'''
convert list to dictionary using the key as the identifier
:param items: array to iterate over
:return: dictionary
'''
if items is None:
items = []
ret = {}
if items and isinstance(items, list):
for item in items:
if 'name' in item:
# added for consistency with old code
if 'id' not in item:
item['id'] = item['name']
ret[item['name']] = item
return ret | python | def key_list(items=None):
'''
convert list to dictionary using the key as the identifier
:param items: array to iterate over
:return: dictionary
'''
if items is None:
items = []
ret = {}
if items and isinstance(items, list):
for item in items:
if 'name' in item:
# added for consistency with old code
if 'id' not in item:
item['id'] = item['name']
ret[item['name']] = item
return ret | [
"def",
"key_list",
"(",
"items",
"=",
"None",
")",
":",
"if",
"items",
"is",
"None",
":",
"items",
"=",
"[",
"]",
"ret",
"=",
"{",
"}",
"if",
"items",
"and",
"isinstance",
"(",
"items",
",",
"list",
")",
":",
"for",
"item",
"in",
"items",
":",
... | convert list to dictionary using the key as the identifier
:param items: array to iterate over
:return: dictionary | [
"convert",
"list",
"to",
"dictionary",
"using",
"the",
"key",
"as",
"the",
"identifier",
":",
"param",
"items",
":",
"array",
"to",
"iterate",
"over",
":",
"return",
":",
"dictionary"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/joyent.py#L601-L618 | train |
saltstack/salt | salt/cloud/clouds/joyent.py | show_instance | def show_instance(name, call=None):
'''
get details about a machine
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: machine information
CLI Example:
.. code-block:: bash
salt-cloud -a show_instance vm_name
'''
node = get_node(name)
ret = query(command='my/machines/{0}'.format(node['id']),
location=node['location'], method='GET')
return ret | python | def show_instance(name, call=None):
'''
get details about a machine
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: machine information
CLI Example:
.. code-block:: bash
salt-cloud -a show_instance vm_name
'''
node = get_node(name)
ret = query(command='my/machines/{0}'.format(node['id']),
location=node['location'], method='GET')
return ret | [
"def",
"show_instance",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"node",
"=",
"get_node",
"(",
"name",
")",
"ret",
"=",
"query",
"(",
"command",
"=",
"'my/machines/{0}'",
".",
"format",
"(",
"node",
"[",
"'id'",
"]",
")",
",",
"location",
"="... | get details about a machine
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: machine information
CLI Example:
.. code-block:: bash
salt-cloud -a show_instance vm_name | [
"get",
"details",
"about",
"a",
"machine",
":",
"param",
"name",
":",
"name",
"given",
"to",
"the",
"machine",
":",
"param",
"call",
":",
"call",
"value",
"in",
"this",
"case",
"is",
"action",
":",
"return",
":",
"machine",
"information"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/joyent.py#L633-L650 | train |
saltstack/salt | salt/cloud/clouds/joyent.py | reformat_node | def reformat_node(item=None, full=False):
'''
Reformat the returned data from joyent, determine public/private IPs and
strip out fields if necessary to provide either full or brief content.
:param item: node dictionary
:param full: full or brief output
:return: dict
'''
desired_keys = [
'id', 'name', 'state', 'public_ips', 'private_ips', 'size', 'image',
'location'
]
item['private_ips'] = []
item['public_ips'] = []
if 'ips' in item:
for ip in item['ips']:
if salt.utils.cloud.is_public_ip(ip):
item['public_ips'].append(ip)
else:
item['private_ips'].append(ip)
# add any undefined desired keys
for key in desired_keys:
if key not in item:
item[key] = None
# remove all the extra key value pairs to provide a brief listing
to_del = []
if not full:
for key in six.iterkeys(item): # iterate over a copy of the keys
if key not in desired_keys:
to_del.append(key)
for key in to_del:
del item[key]
if 'state' in item:
item['state'] = joyent_node_state(item['state'])
return item | python | def reformat_node(item=None, full=False):
'''
Reformat the returned data from joyent, determine public/private IPs and
strip out fields if necessary to provide either full or brief content.
:param item: node dictionary
:param full: full or brief output
:return: dict
'''
desired_keys = [
'id', 'name', 'state', 'public_ips', 'private_ips', 'size', 'image',
'location'
]
item['private_ips'] = []
item['public_ips'] = []
if 'ips' in item:
for ip in item['ips']:
if salt.utils.cloud.is_public_ip(ip):
item['public_ips'].append(ip)
else:
item['private_ips'].append(ip)
# add any undefined desired keys
for key in desired_keys:
if key not in item:
item[key] = None
# remove all the extra key value pairs to provide a brief listing
to_del = []
if not full:
for key in six.iterkeys(item): # iterate over a copy of the keys
if key not in desired_keys:
to_del.append(key)
for key in to_del:
del item[key]
if 'state' in item:
item['state'] = joyent_node_state(item['state'])
return item | [
"def",
"reformat_node",
"(",
"item",
"=",
"None",
",",
"full",
"=",
"False",
")",
":",
"desired_keys",
"=",
"[",
"'id'",
",",
"'name'",
",",
"'state'",
",",
"'public_ips'",
",",
"'private_ips'",
",",
"'size'",
",",
"'image'",
",",
"'location'",
"]",
"ite... | Reformat the returned data from joyent, determine public/private IPs and
strip out fields if necessary to provide either full or brief content.
:param item: node dictionary
:param full: full or brief output
:return: dict | [
"Reformat",
"the",
"returned",
"data",
"from",
"joyent",
"determine",
"public",
"/",
"private",
"IPs",
"and",
"strip",
"out",
"fields",
"if",
"necessary",
"to",
"provide",
"either",
"full",
"or",
"brief",
"content",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/joyent.py#L674-L714 | train |
saltstack/salt | salt/cloud/clouds/joyent.py | list_nodes | def list_nodes(full=False, call=None):
'''
list of nodes, keeping only a brief listing
CLI Example:
.. code-block:: bash
salt-cloud -Q
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
if POLL_ALL_LOCATIONS:
for location in JOYENT_LOCATIONS:
result = query(command='my/machines', location=location,
method='GET')
if result[0] in VALID_RESPONSE_CODES:
nodes = result[1]
for node in nodes:
if 'name' in node:
node['location'] = location
ret[node['name']] = reformat_node(item=node, full=full)
else:
log.error('Invalid response when listing Joyent nodes: %s', result[1])
else:
location = get_location()
result = query(command='my/machines', location=location,
method='GET')
nodes = result[1]
for node in nodes:
if 'name' in node:
node['location'] = location
ret[node['name']] = reformat_node(item=node, full=full)
return ret | python | def list_nodes(full=False, call=None):
'''
list of nodes, keeping only a brief listing
CLI Example:
.. code-block:: bash
salt-cloud -Q
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
if POLL_ALL_LOCATIONS:
for location in JOYENT_LOCATIONS:
result = query(command='my/machines', location=location,
method='GET')
if result[0] in VALID_RESPONSE_CODES:
nodes = result[1]
for node in nodes:
if 'name' in node:
node['location'] = location
ret[node['name']] = reformat_node(item=node, full=full)
else:
log.error('Invalid response when listing Joyent nodes: %s', result[1])
else:
location = get_location()
result = query(command='my/machines', location=location,
method='GET')
nodes = result[1]
for node in nodes:
if 'name' in node:
node['location'] = location
ret[node['name']] = reformat_node(item=node, full=full)
return ret | [
"def",
"list_nodes",
"(",
"full",
"=",
"False",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_nodes function must be called with -f or --function.'",
")",
"ret",
"=",
"{",
"}",
"if",
"POL... | list of nodes, keeping only a brief listing
CLI Example:
.. code-block:: bash
salt-cloud -Q | [
"list",
"of",
"nodes",
"keeping",
"only",
"a",
"brief",
"listing"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/joyent.py#L717-L755 | train |
saltstack/salt | salt/cloud/clouds/joyent.py | _get_proto | def _get_proto():
'''
Checks configuration to see whether the user has SSL turned on. Default is:
.. code-block:: yaml
use_ssl: True
'''
use_ssl = config.get_cloud_config_value(
'use_ssl',
get_configured_provider(),
__opts__,
search_global=False,
default=True
)
if use_ssl is True:
return 'https'
return 'http' | python | def _get_proto():
'''
Checks configuration to see whether the user has SSL turned on. Default is:
.. code-block:: yaml
use_ssl: True
'''
use_ssl = config.get_cloud_config_value(
'use_ssl',
get_configured_provider(),
__opts__,
search_global=False,
default=True
)
if use_ssl is True:
return 'https'
return 'http' | [
"def",
"_get_proto",
"(",
")",
":",
"use_ssl",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'use_ssl'",
",",
"get_configured_provider",
"(",
")",
",",
"__opts__",
",",
"search_global",
"=",
"False",
",",
"default",
"=",
"True",
")",
"if",
"use_ssl",
"... | Checks configuration to see whether the user has SSL turned on. Default is:
.. code-block:: yaml
use_ssl: True | [
"Checks",
"configuration",
"to",
"see",
"whether",
"the",
"user",
"has",
"SSL",
"turned",
"on",
".",
"Default",
"is",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/joyent.py#L785-L802 | train |
saltstack/salt | salt/cloud/clouds/joyent.py | avail_images | def avail_images(call=None):
'''
Get list of available images
CLI Example:
.. code-block:: bash
salt-cloud --list-images
Can use a custom URL for images. Default is:
.. code-block:: yaml
image_url: images.joyent.com/images
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
user = config.get_cloud_config_value(
'user', get_configured_provider(), __opts__, search_global=False
)
img_url = config.get_cloud_config_value(
'image_url',
get_configured_provider(),
__opts__,
search_global=False,
default='{0}{1}/{2}/images'.format(DEFAULT_LOCATION, JOYENT_API_HOST_SUFFIX, user)
)
if not img_url.startswith('http://') and not img_url.startswith('https://'):
img_url = '{0}://{1}'.format(_get_proto(), img_url)
rcode, data = query(command='my/images', method='GET')
log.debug(data)
ret = {}
for image in data:
ret[image['name']] = image
return ret | python | def avail_images(call=None):
'''
Get list of available images
CLI Example:
.. code-block:: bash
salt-cloud --list-images
Can use a custom URL for images. Default is:
.. code-block:: yaml
image_url: images.joyent.com/images
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
user = config.get_cloud_config_value(
'user', get_configured_provider(), __opts__, search_global=False
)
img_url = config.get_cloud_config_value(
'image_url',
get_configured_provider(),
__opts__,
search_global=False,
default='{0}{1}/{2}/images'.format(DEFAULT_LOCATION, JOYENT_API_HOST_SUFFIX, user)
)
if not img_url.startswith('http://') and not img_url.startswith('https://'):
img_url = '{0}://{1}'.format(_get_proto(), img_url)
rcode, data = query(command='my/images', method='GET')
log.debug(data)
ret = {}
for image in data:
ret[image['name']] = image
return ret | [
"def",
"avail_images",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The avail_images function must be called with '",
"'-f or --function, or with the --list-images option'",
")",
"user",
"=",
"config",
"."... | Get list of available images
CLI Example:
.. code-block:: bash
salt-cloud --list-images
Can use a custom URL for images. Default is:
.. code-block:: yaml
image_url: images.joyent.com/images | [
"Get",
"list",
"of",
"available",
"images"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/joyent.py#L805-L848 | train |
saltstack/salt | salt/cloud/clouds/joyent.py | avail_sizes | def avail_sizes(call=None):
'''
get list of available packages
CLI Example:
.. code-block:: bash
salt-cloud --list-sizes
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
rcode, items = query(command='my/packages')
if rcode not in VALID_RESPONSE_CODES:
return {}
return key_list(items=items) | python | def avail_sizes(call=None):
'''
get list of available packages
CLI Example:
.. code-block:: bash
salt-cloud --list-sizes
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
rcode, items = query(command='my/packages')
if rcode not in VALID_RESPONSE_CODES:
return {}
return key_list(items=items) | [
"def",
"avail_sizes",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The avail_sizes function must be called with '",
"'-f or --function, or with the --list-sizes option'",
")",
"rcode",
",",
"items",
"=",
... | get list of available packages
CLI Example:
.. code-block:: bash
salt-cloud --list-sizes | [
"get",
"list",
"of",
"available",
"packages"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/joyent.py#L851-L870 | train |
saltstack/salt | salt/cloud/clouds/joyent.py | list_keys | def list_keys(kwargs=None, call=None):
'''
List the keys available
'''
if call != 'function':
log.error(
'The list_keys function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
ret = {}
rcode, data = query(command='my/keys', method='GET')
for pair in data:
ret[pair['name']] = pair['key']
return {'keys': ret} | python | def list_keys(kwargs=None, call=None):
'''
List the keys available
'''
if call != 'function':
log.error(
'The list_keys function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
ret = {}
rcode, data = query(command='my/keys', method='GET')
for pair in data:
ret[pair['name']] = pair['key']
return {'keys': ret} | [
"def",
"list_keys",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"log",
".",
"error",
"(",
"'The list_keys function must be called with -f or --function.'",
")",
"return",
"False",
"if",
"not",
"kwargs",
... | List the keys available | [
"List",
"the",
"keys",
"available"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/joyent.py#L873-L890 | train |
saltstack/salt | salt/cloud/clouds/joyent.py | show_key | def show_key(kwargs=None, call=None):
'''
List the keys available
'''
if call != 'function':
log.error(
'The list_keys function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
rcode, data = query(
command='my/keys/{0}'.format(kwargs['keyname']),
method='GET',
)
return {'keys': {data['name']: data['key']}} | python | def show_key(kwargs=None, call=None):
'''
List the keys available
'''
if call != 'function':
log.error(
'The list_keys function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
rcode, data = query(
command='my/keys/{0}'.format(kwargs['keyname']),
method='GET',
)
return {'keys': {data['name']: data['key']}} | [
"def",
"show_key",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"log",
".",
"error",
"(",
"'The list_keys function must be called with -f or --function.'",
")",
"return",
"False",
"if",
"not",
"kwargs",
... | List the keys available | [
"List",
"the",
"keys",
"available"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/joyent.py#L893-L914 | train |
saltstack/salt | salt/cloud/clouds/joyent.py | import_key | def import_key(kwargs=None, call=None):
'''
List the keys available
CLI Example:
.. code-block:: bash
salt-cloud -f import_key joyent keyname=mykey keyfile=/tmp/mykey.pub
'''
if call != 'function':
log.error(
'The import_key function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
if 'keyfile' not in kwargs:
log.error('The location of the SSH keyfile is required.')
return False
if not os.path.isfile(kwargs['keyfile']):
log.error('The specified keyfile (%s) does not exist.', kwargs['keyfile'])
return False
with salt.utils.files.fopen(kwargs['keyfile'], 'r') as fp_:
kwargs['key'] = salt.utils.stringutils.to_unicode(fp_.read())
send_data = {'name': kwargs['keyname'], 'key': kwargs['key']}
kwargs['data'] = salt.utils.json.dumps(send_data)
rcode, data = query(
command='my/keys',
method='POST',
data=kwargs['data'],
)
log.debug(pprint.pformat(data))
return {'keys': {data['name']: data['key']}} | python | def import_key(kwargs=None, call=None):
'''
List the keys available
CLI Example:
.. code-block:: bash
salt-cloud -f import_key joyent keyname=mykey keyfile=/tmp/mykey.pub
'''
if call != 'function':
log.error(
'The import_key function must be called with -f or --function.'
)
return False
if not kwargs:
kwargs = {}
if 'keyname' not in kwargs:
log.error('A keyname is required.')
return False
if 'keyfile' not in kwargs:
log.error('The location of the SSH keyfile is required.')
return False
if not os.path.isfile(kwargs['keyfile']):
log.error('The specified keyfile (%s) does not exist.', kwargs['keyfile'])
return False
with salt.utils.files.fopen(kwargs['keyfile'], 'r') as fp_:
kwargs['key'] = salt.utils.stringutils.to_unicode(fp_.read())
send_data = {'name': kwargs['keyname'], 'key': kwargs['key']}
kwargs['data'] = salt.utils.json.dumps(send_data)
rcode, data = query(
command='my/keys',
method='POST',
data=kwargs['data'],
)
log.debug(pprint.pformat(data))
return {'keys': {data['name']: data['key']}} | [
"def",
"import_key",
"(",
"kwargs",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"log",
".",
"error",
"(",
"'The import_key function must be called with -f or --function.'",
")",
"return",
"False",
"if",
"not",
"kwargs"... | List the keys available
CLI Example:
.. code-block:: bash
salt-cloud -f import_key joyent keyname=mykey keyfile=/tmp/mykey.pub | [
"List",
"the",
"keys",
"available"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/joyent.py#L917-L960 | train |
saltstack/salt | salt/cloud/clouds/joyent.py | query | def query(action=None,
command=None,
args=None,
method='GET',
location=None,
data=None):
'''
Make a web call to Joyent
'''
user = config.get_cloud_config_value(
'user', get_configured_provider(), __opts__, search_global=False
)
if not user:
log.error('username is required for Joyent API requests. Please set one in your provider configuration')
password = config.get_cloud_config_value(
'password', get_configured_provider(), __opts__,
search_global=False
)
verify_ssl = config.get_cloud_config_value(
'verify_ssl', get_configured_provider(), __opts__,
search_global=False, default=True
)
ssh_keyfile = config.get_cloud_config_value(
'private_key', get_configured_provider(), __opts__,
search_global=False, default=True
)
if not ssh_keyfile:
log.error('ssh_keyfile is required for Joyent API requests. Please set one in your provider configuration')
ssh_keyname = config.get_cloud_config_value(
'keyname', get_configured_provider(), __opts__,
search_global=False, default=True
)
if not ssh_keyname:
log.error('ssh_keyname is required for Joyent API requests. Please set one in your provider configuration')
if not location:
location = get_location()
api_host_suffix = config.get_cloud_config_value(
'api_host_suffix', get_configured_provider(), __opts__,
search_global=False, default=JOYENT_API_HOST_SUFFIX
)
path = get_location_path(location=location, api_host_suffix=api_host_suffix)
if action:
path += action
if command:
path += '/{0}'.format(command)
log.debug('User: \'%s\' on PATH: %s', user, path)
if (not user) or (not ssh_keyfile) or (not ssh_keyname) or (not location):
return None
timenow = datetime.datetime.utcnow()
timestamp = timenow.strftime('%a, %d %b %Y %H:%M:%S %Z').strip()
rsa_key = salt.crypt.get_rsa_key(ssh_keyfile, None)
if HAS_M2:
md = EVP.MessageDigest('sha256')
md.update(timestamp.encode(__salt_system_encoding__))
digest = md.final()
signed = rsa_key.sign(digest, algo='sha256')
else:
rsa_ = PKCS1_v1_5.new(rsa_key)
hash_ = SHA256.new()
hash_.update(timestamp.encode(__salt_system_encoding__))
signed = rsa_.sign(hash_)
signed = base64.b64encode(signed)
user_arr = user.split('/')
if len(user_arr) == 1:
keyid = '/{0}/keys/{1}'.format(user_arr[0], ssh_keyname)
elif len(user_arr) == 2:
keyid = '/{0}/users/{1}/keys/{2}'.format(user_arr[0], user_arr[1], ssh_keyname)
else:
log.error('Malformed user string')
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-Api-Version': JOYENT_API_VERSION,
'Date': timestamp,
'Authorization': 'Signature keyId="{0}",algorithm="rsa-sha256" {1}'.format(
keyid,
signed.decode(__salt_system_encoding__)
),
}
if not isinstance(args, dict):
args = {}
# post form data
if not data:
data = salt.utils.json.dumps({})
return_content = None
result = salt.utils.http.query(
path,
method,
params=args,
header_dict=headers,
data=data,
decode=False,
text=True,
status=True,
headers=True,
verify_ssl=verify_ssl,
opts=__opts__,
)
log.debug('Joyent Response Status Code: %s', result['status'])
if 'headers' not in result:
return [result['status'], result['error']]
if 'Content-Length' in result['headers']:
content = result['text']
return_content = salt.utils.yaml.safe_load(content)
return [result['status'], return_content] | python | def query(action=None,
command=None,
args=None,
method='GET',
location=None,
data=None):
'''
Make a web call to Joyent
'''
user = config.get_cloud_config_value(
'user', get_configured_provider(), __opts__, search_global=False
)
if not user:
log.error('username is required for Joyent API requests. Please set one in your provider configuration')
password = config.get_cloud_config_value(
'password', get_configured_provider(), __opts__,
search_global=False
)
verify_ssl = config.get_cloud_config_value(
'verify_ssl', get_configured_provider(), __opts__,
search_global=False, default=True
)
ssh_keyfile = config.get_cloud_config_value(
'private_key', get_configured_provider(), __opts__,
search_global=False, default=True
)
if not ssh_keyfile:
log.error('ssh_keyfile is required for Joyent API requests. Please set one in your provider configuration')
ssh_keyname = config.get_cloud_config_value(
'keyname', get_configured_provider(), __opts__,
search_global=False, default=True
)
if not ssh_keyname:
log.error('ssh_keyname is required for Joyent API requests. Please set one in your provider configuration')
if not location:
location = get_location()
api_host_suffix = config.get_cloud_config_value(
'api_host_suffix', get_configured_provider(), __opts__,
search_global=False, default=JOYENT_API_HOST_SUFFIX
)
path = get_location_path(location=location, api_host_suffix=api_host_suffix)
if action:
path += action
if command:
path += '/{0}'.format(command)
log.debug('User: \'%s\' on PATH: %s', user, path)
if (not user) or (not ssh_keyfile) or (not ssh_keyname) or (not location):
return None
timenow = datetime.datetime.utcnow()
timestamp = timenow.strftime('%a, %d %b %Y %H:%M:%S %Z').strip()
rsa_key = salt.crypt.get_rsa_key(ssh_keyfile, None)
if HAS_M2:
md = EVP.MessageDigest('sha256')
md.update(timestamp.encode(__salt_system_encoding__))
digest = md.final()
signed = rsa_key.sign(digest, algo='sha256')
else:
rsa_ = PKCS1_v1_5.new(rsa_key)
hash_ = SHA256.new()
hash_.update(timestamp.encode(__salt_system_encoding__))
signed = rsa_.sign(hash_)
signed = base64.b64encode(signed)
user_arr = user.split('/')
if len(user_arr) == 1:
keyid = '/{0}/keys/{1}'.format(user_arr[0], ssh_keyname)
elif len(user_arr) == 2:
keyid = '/{0}/users/{1}/keys/{2}'.format(user_arr[0], user_arr[1], ssh_keyname)
else:
log.error('Malformed user string')
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-Api-Version': JOYENT_API_VERSION,
'Date': timestamp,
'Authorization': 'Signature keyId="{0}",algorithm="rsa-sha256" {1}'.format(
keyid,
signed.decode(__salt_system_encoding__)
),
}
if not isinstance(args, dict):
args = {}
# post form data
if not data:
data = salt.utils.json.dumps({})
return_content = None
result = salt.utils.http.query(
path,
method,
params=args,
header_dict=headers,
data=data,
decode=False,
text=True,
status=True,
headers=True,
verify_ssl=verify_ssl,
opts=__opts__,
)
log.debug('Joyent Response Status Code: %s', result['status'])
if 'headers' not in result:
return [result['status'], result['error']]
if 'Content-Length' in result['headers']:
content = result['text']
return_content = salt.utils.yaml.safe_load(content)
return [result['status'], return_content] | [
"def",
"query",
"(",
"action",
"=",
"None",
",",
"command",
"=",
"None",
",",
"args",
"=",
"None",
",",
"method",
"=",
"'GET'",
",",
"location",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"user",
"=",
"config",
".",
"get_cloud_config_value",
"(... | Make a web call to Joyent | [
"Make",
"a",
"web",
"call",
"to",
"Joyent"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/joyent.py#L1002-L1127 | train |
saltstack/salt | salt/modules/upstart_service.py | _find_utmp | def _find_utmp():
'''
Figure out which utmp file to use when determining runlevel.
Sometimes /var/run/utmp doesn't exist, /run/utmp is the new hotness.
'''
result = {}
# These are the likely locations for the file on Ubuntu
for utmp in '/var/run/utmp', '/run/utmp':
try:
result[os.stat(utmp).st_mtime] = utmp
except Exception:
pass
if result:
return result[sorted(result).pop()]
else:
return False | python | def _find_utmp():
'''
Figure out which utmp file to use when determining runlevel.
Sometimes /var/run/utmp doesn't exist, /run/utmp is the new hotness.
'''
result = {}
# These are the likely locations for the file on Ubuntu
for utmp in '/var/run/utmp', '/run/utmp':
try:
result[os.stat(utmp).st_mtime] = utmp
except Exception:
pass
if result:
return result[sorted(result).pop()]
else:
return False | [
"def",
"_find_utmp",
"(",
")",
":",
"result",
"=",
"{",
"}",
"# These are the likely locations for the file on Ubuntu",
"for",
"utmp",
"in",
"'/var/run/utmp'",
",",
"'/run/utmp'",
":",
"try",
":",
"result",
"[",
"os",
".",
"stat",
"(",
"utmp",
")",
".",
"st_mt... | Figure out which utmp file to use when determining runlevel.
Sometimes /var/run/utmp doesn't exist, /run/utmp is the new hotness. | [
"Figure",
"out",
"which",
"utmp",
"file",
"to",
"use",
"when",
"determining",
"runlevel",
".",
"Sometimes",
"/",
"var",
"/",
"run",
"/",
"utmp",
"doesn",
"t",
"exist",
"/",
"run",
"/",
"utmp",
"is",
"the",
"new",
"hotness",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/upstart_service.py#L89-L104 | train |
saltstack/salt | salt/modules/upstart_service.py | _runlevel | def _runlevel():
'''
Return the current runlevel
'''
if 'upstart._runlevel' in __context__:
return __context__['upstart._runlevel']
ret = _default_runlevel()
utmp = _find_utmp()
if utmp:
out = __salt__['cmd.run'](['runlevel', '{0}'.format(utmp)], python_shell=False)
try:
ret = out.split()[1]
except IndexError:
pass
__context__['upstart._runlevel'] = ret
return ret | python | def _runlevel():
'''
Return the current runlevel
'''
if 'upstart._runlevel' in __context__:
return __context__['upstart._runlevel']
ret = _default_runlevel()
utmp = _find_utmp()
if utmp:
out = __salt__['cmd.run'](['runlevel', '{0}'.format(utmp)], python_shell=False)
try:
ret = out.split()[1]
except IndexError:
pass
__context__['upstart._runlevel'] = ret
return ret | [
"def",
"_runlevel",
"(",
")",
":",
"if",
"'upstart._runlevel'",
"in",
"__context__",
":",
"return",
"__context__",
"[",
"'upstart._runlevel'",
"]",
"ret",
"=",
"_default_runlevel",
"(",
")",
"utmp",
"=",
"_find_utmp",
"(",
")",
"if",
"utmp",
":",
"out",
"=",... | Return the current runlevel | [
"Return",
"the",
"current",
"runlevel"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/upstart_service.py#L152-L167 | train |
saltstack/salt | salt/modules/upstart_service.py | _upstart_is_disabled | def _upstart_is_disabled(name):
'''
An Upstart service is assumed disabled if a manual stanza is
placed in /etc/init/[name].override.
NOTE: An Upstart service can also be disabled by placing "manual"
in /etc/init/[name].conf.
'''
files = ['/etc/init/{0}.conf'.format(name), '/etc/init/{0}.override'.format(name)]
for file_name in filter(os.path.isfile, files):
with salt.utils.files.fopen(file_name) as fp_:
if re.search(r'^\s*manual',
salt.utils.stringutils.to_unicode(fp_.read()),
re.MULTILINE):
return True
return False | python | def _upstart_is_disabled(name):
'''
An Upstart service is assumed disabled if a manual stanza is
placed in /etc/init/[name].override.
NOTE: An Upstart service can also be disabled by placing "manual"
in /etc/init/[name].conf.
'''
files = ['/etc/init/{0}.conf'.format(name), '/etc/init/{0}.override'.format(name)]
for file_name in filter(os.path.isfile, files):
with salt.utils.files.fopen(file_name) as fp_:
if re.search(r'^\s*manual',
salt.utils.stringutils.to_unicode(fp_.read()),
re.MULTILINE):
return True
return False | [
"def",
"_upstart_is_disabled",
"(",
"name",
")",
":",
"files",
"=",
"[",
"'/etc/init/{0}.conf'",
".",
"format",
"(",
"name",
")",
",",
"'/etc/init/{0}.override'",
".",
"format",
"(",
"name",
")",
"]",
"for",
"file_name",
"in",
"filter",
"(",
"os",
".",
"pa... | An Upstart service is assumed disabled if a manual stanza is
placed in /etc/init/[name].override.
NOTE: An Upstart service can also be disabled by placing "manual"
in /etc/init/[name].conf. | [
"An",
"Upstart",
"service",
"is",
"assumed",
"disabled",
"if",
"a",
"manual",
"stanza",
"is",
"placed",
"in",
"/",
"etc",
"/",
"init",
"/",
"[",
"name",
"]",
".",
"override",
".",
"NOTE",
":",
"An",
"Upstart",
"service",
"can",
"also",
"be",
"disabled"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/upstart_service.py#L185-L199 | train |
saltstack/salt | salt/modules/upstart_service.py | _service_is_sysv | def _service_is_sysv(name):
'''
A System-V style service will have a control script in
/etc/init.d. We make sure to skip over symbolic links that point
to Upstart's /lib/init/upstart-job, and anything that isn't an
executable, like README or skeleton.
'''
script = '/etc/init.d/{0}'.format(name)
return not _service_is_upstart(name) and os.access(script, os.X_OK) | python | def _service_is_sysv(name):
'''
A System-V style service will have a control script in
/etc/init.d. We make sure to skip over symbolic links that point
to Upstart's /lib/init/upstart-job, and anything that isn't an
executable, like README or skeleton.
'''
script = '/etc/init.d/{0}'.format(name)
return not _service_is_upstart(name) and os.access(script, os.X_OK) | [
"def",
"_service_is_sysv",
"(",
"name",
")",
":",
"script",
"=",
"'/etc/init.d/{0}'",
".",
"format",
"(",
"name",
")",
"return",
"not",
"_service_is_upstart",
"(",
"name",
")",
"and",
"os",
".",
"access",
"(",
"script",
",",
"os",
".",
"X_OK",
")"
] | A System-V style service will have a control script in
/etc/init.d. We make sure to skip over symbolic links that point
to Upstart's /lib/init/upstart-job, and anything that isn't an
executable, like README or skeleton. | [
"A",
"System",
"-",
"V",
"style",
"service",
"will",
"have",
"a",
"control",
"script",
"in",
"/",
"etc",
"/",
"init",
".",
"d",
".",
"We",
"make",
"sure",
"to",
"skip",
"over",
"symbolic",
"links",
"that",
"point",
"to",
"Upstart",
"s",
"/",
"lib",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/upstart_service.py#L210-L218 | train |
saltstack/salt | salt/modules/upstart_service.py | _iter_service_names | def _iter_service_names():
'''
Detect all of the service names available to upstart via init configuration
files and via classic sysv init scripts
'''
found = set()
for line in glob.glob('/etc/init.d/*'):
name = os.path.basename(line)
found.add(name)
yield name
# This walk method supports nested services as per the init man page
# definition 'For example a configuration file /etc/init/rc-sysinit.conf
# is named rc-sysinit, while a configuration file /etc/init/net/apache.conf
# is named net/apache'
init_root = '/etc/init/'
for root, dirnames, filenames in salt.utils.path.os_walk(init_root):
relpath = os.path.relpath(root, init_root)
for filename in fnmatch.filter(filenames, '*.conf'):
if relpath == '.':
# service is defined in the root, no need to append prefix.
name = filename[:-5]
else:
# service is nested, append its relative path prefix.
name = os.path.join(relpath, filename[:-5])
if name in found:
continue
yield name | python | def _iter_service_names():
'''
Detect all of the service names available to upstart via init configuration
files and via classic sysv init scripts
'''
found = set()
for line in glob.glob('/etc/init.d/*'):
name = os.path.basename(line)
found.add(name)
yield name
# This walk method supports nested services as per the init man page
# definition 'For example a configuration file /etc/init/rc-sysinit.conf
# is named rc-sysinit, while a configuration file /etc/init/net/apache.conf
# is named net/apache'
init_root = '/etc/init/'
for root, dirnames, filenames in salt.utils.path.os_walk(init_root):
relpath = os.path.relpath(root, init_root)
for filename in fnmatch.filter(filenames, '*.conf'):
if relpath == '.':
# service is defined in the root, no need to append prefix.
name = filename[:-5]
else:
# service is nested, append its relative path prefix.
name = os.path.join(relpath, filename[:-5])
if name in found:
continue
yield name | [
"def",
"_iter_service_names",
"(",
")",
":",
"found",
"=",
"set",
"(",
")",
"for",
"line",
"in",
"glob",
".",
"glob",
"(",
"'/etc/init.d/*'",
")",
":",
"name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"line",
")",
"found",
".",
"add",
"(",
"na... | Detect all of the service names available to upstart via init configuration
files and via classic sysv init scripts | [
"Detect",
"all",
"of",
"the",
"service",
"names",
"available",
"to",
"upstart",
"via",
"init",
"configuration",
"files",
"and",
"via",
"classic",
"sysv",
"init",
"scripts"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/upstart_service.py#L238-L265 | train |
saltstack/salt | salt/modules/upstart_service.py | get_enabled | def get_enabled():
'''
Return the enabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_enabled
'''
ret = set()
for name in _iter_service_names():
if _service_is_upstart(name):
if _upstart_is_enabled(name):
ret.add(name)
else:
if _service_is_sysv(name):
if _sysv_is_enabled(name):
ret.add(name)
return sorted(ret) | python | def get_enabled():
'''
Return the enabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_enabled
'''
ret = set()
for name in _iter_service_names():
if _service_is_upstart(name):
if _upstart_is_enabled(name):
ret.add(name)
else:
if _service_is_sysv(name):
if _sysv_is_enabled(name):
ret.add(name)
return sorted(ret) | [
"def",
"get_enabled",
"(",
")",
":",
"ret",
"=",
"set",
"(",
")",
"for",
"name",
"in",
"_iter_service_names",
"(",
")",
":",
"if",
"_service_is_upstart",
"(",
"name",
")",
":",
"if",
"_upstart_is_enabled",
"(",
"name",
")",
":",
"ret",
".",
"add",
"(",... | Return the enabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_enabled | [
"Return",
"the",
"enabled",
"services"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/upstart_service.py#L268-L287 | train |
saltstack/salt | salt/modules/upstart_service.py | get_disabled | def get_disabled():
'''
Return the disabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled
'''
ret = set()
for name in _iter_service_names():
if _service_is_upstart(name):
if _upstart_is_disabled(name):
ret.add(name)
else:
if _service_is_sysv(name):
if _sysv_is_disabled(name):
ret.add(name)
return sorted(ret) | python | def get_disabled():
'''
Return the disabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled
'''
ret = set()
for name in _iter_service_names():
if _service_is_upstart(name):
if _upstart_is_disabled(name):
ret.add(name)
else:
if _service_is_sysv(name):
if _sysv_is_disabled(name):
ret.add(name)
return sorted(ret) | [
"def",
"get_disabled",
"(",
")",
":",
"ret",
"=",
"set",
"(",
")",
"for",
"name",
"in",
"_iter_service_names",
"(",
")",
":",
"if",
"_service_is_upstart",
"(",
"name",
")",
":",
"if",
"_upstart_is_disabled",
"(",
"name",
")",
":",
"ret",
".",
"add",
"(... | Return the disabled services
CLI Example:
.. code-block:: bash
salt '*' service.get_disabled | [
"Return",
"the",
"disabled",
"services"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/upstart_service.py#L290-L309 | train |
saltstack/salt | salt/modules/upstart_service.py | _upstart_disable | def _upstart_disable(name):
'''
Disable an Upstart service.
'''
if _upstart_is_disabled(name):
return _upstart_is_disabled(name)
override = '/etc/init/{0}.override'.format(name)
with salt.utils.files.fopen(override, 'a') as ofile:
ofile.write(salt.utils.stringutils.to_str('manual\n'))
return _upstart_is_disabled(name) | python | def _upstart_disable(name):
'''
Disable an Upstart service.
'''
if _upstart_is_disabled(name):
return _upstart_is_disabled(name)
override = '/etc/init/{0}.override'.format(name)
with salt.utils.files.fopen(override, 'a') as ofile:
ofile.write(salt.utils.stringutils.to_str('manual\n'))
return _upstart_is_disabled(name) | [
"def",
"_upstart_disable",
"(",
"name",
")",
":",
"if",
"_upstart_is_disabled",
"(",
"name",
")",
":",
"return",
"_upstart_is_disabled",
"(",
"name",
")",
"override",
"=",
"'/etc/init/{0}.override'",
".",
"format",
"(",
"name",
")",
"with",
"salt",
".",
"utils... | Disable an Upstart service. | [
"Disable",
"an",
"Upstart",
"service",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/upstart_service.py#L499-L508 | train |
saltstack/salt | salt/modules/upstart_service.py | _upstart_enable | def _upstart_enable(name):
'''
Enable an Upstart service.
'''
if _upstart_is_enabled(name):
return _upstart_is_enabled(name)
override = '/etc/init/{0}.override'.format(name)
files = ['/etc/init/{0}.conf'.format(name), override]
for file_name in filter(os.path.isfile, files):
with salt.utils.files.fopen(file_name, 'r+') as fp_:
new_text = re.sub(r'^\s*manual\n?',
'',
salt.utils.stringutils.to_unicode(fp_.read()),
0,
re.MULTILINE)
fp_.seek(0)
fp_.write(
salt.utils.stringutils.to_str(
new_text
)
)
fp_.truncate()
if os.access(override, os.R_OK) and os.path.getsize(override) == 0:
os.unlink(override)
return _upstart_is_enabled(name) | python | def _upstart_enable(name):
'''
Enable an Upstart service.
'''
if _upstart_is_enabled(name):
return _upstart_is_enabled(name)
override = '/etc/init/{0}.override'.format(name)
files = ['/etc/init/{0}.conf'.format(name), override]
for file_name in filter(os.path.isfile, files):
with salt.utils.files.fopen(file_name, 'r+') as fp_:
new_text = re.sub(r'^\s*manual\n?',
'',
salt.utils.stringutils.to_unicode(fp_.read()),
0,
re.MULTILINE)
fp_.seek(0)
fp_.write(
salt.utils.stringutils.to_str(
new_text
)
)
fp_.truncate()
if os.access(override, os.R_OK) and os.path.getsize(override) == 0:
os.unlink(override)
return _upstart_is_enabled(name) | [
"def",
"_upstart_enable",
"(",
"name",
")",
":",
"if",
"_upstart_is_enabled",
"(",
"name",
")",
":",
"return",
"_upstart_is_enabled",
"(",
"name",
")",
"override",
"=",
"'/etc/init/{0}.override'",
".",
"format",
"(",
"name",
")",
"files",
"=",
"[",
"'/etc/init... | Enable an Upstart service. | [
"Enable",
"an",
"Upstart",
"service",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/upstart_service.py#L511-L535 | train |
saltstack/salt | salt/modules/upstart_service.py | enable | def enable(name, **kwargs):
'''
Enable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.enable <service name>
'''
if _service_is_upstart(name):
return _upstart_enable(name)
executable = _get_service_exec()
cmd = '{0} -f {1} defaults'.format(executable, name)
return not __salt__['cmd.retcode'](cmd, python_shell=False) | python | def enable(name, **kwargs):
'''
Enable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.enable <service name>
'''
if _service_is_upstart(name):
return _upstart_enable(name)
executable = _get_service_exec()
cmd = '{0} -f {1} defaults'.format(executable, name)
return not __salt__['cmd.retcode'](cmd, python_shell=False) | [
"def",
"enable",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"_service_is_upstart",
"(",
"name",
")",
":",
"return",
"_upstart_enable",
"(",
"name",
")",
"executable",
"=",
"_get_service_exec",
"(",
")",
"cmd",
"=",
"'{0} -f {1} defaults'",
".",
... | Enable the named service to start at boot
CLI Example:
.. code-block:: bash
salt '*' service.enable <service name> | [
"Enable",
"the",
"named",
"service",
"to",
"start",
"at",
"boot"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/upstart_service.py#L538-L552 | train |
saltstack/salt | salt/modules/upstart_service.py | disable | def disable(name, **kwargs):
'''
Disable the named service from starting on boot
CLI Example:
.. code-block:: bash
salt '*' service.disable <service name>
'''
if _service_is_upstart(name):
return _upstart_disable(name)
executable = _get_service_exec()
cmd = [executable, '-f', name, 'remove']
return not __salt__['cmd.retcode'](cmd, python_shell=False) | python | def disable(name, **kwargs):
'''
Disable the named service from starting on boot
CLI Example:
.. code-block:: bash
salt '*' service.disable <service name>
'''
if _service_is_upstart(name):
return _upstart_disable(name)
executable = _get_service_exec()
cmd = [executable, '-f', name, 'remove']
return not __salt__['cmd.retcode'](cmd, python_shell=False) | [
"def",
"disable",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"_service_is_upstart",
"(",
"name",
")",
":",
"return",
"_upstart_disable",
"(",
"name",
")",
"executable",
"=",
"_get_service_exec",
"(",
")",
"cmd",
"=",
"[",
"executable",
",",
"'... | Disable the named service from starting on boot
CLI Example:
.. code-block:: bash
salt '*' service.disable <service name> | [
"Disable",
"the",
"named",
"service",
"from",
"starting",
"on",
"boot"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/upstart_service.py#L555-L569 | train |
saltstack/salt | salt/modules/upstart_service.py | enabled | def enabled(name, **kwargs):
'''
Check to see if the named service is enabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service name>
'''
if _service_is_upstart(name):
return _upstart_is_enabled(name)
else:
if _service_is_sysv(name):
return _sysv_is_enabled(name)
return None | python | def enabled(name, **kwargs):
'''
Check to see if the named service is enabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service name>
'''
if _service_is_upstart(name):
return _upstart_is_enabled(name)
else:
if _service_is_sysv(name):
return _sysv_is_enabled(name)
return None | [
"def",
"enabled",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"_service_is_upstart",
"(",
"name",
")",
":",
"return",
"_upstart_is_enabled",
"(",
"name",
")",
"else",
":",
"if",
"_service_is_sysv",
"(",
"name",
")",
":",
"return",
"_sysv_is_enabl... | Check to see if the named service is enabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.enabled <service name> | [
"Check",
"to",
"see",
"if",
"the",
"named",
"service",
"is",
"enabled",
"to",
"start",
"on",
"boot"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/upstart_service.py#L572-L587 | train |
saltstack/salt | salt/modules/upstart_service.py | disabled | def disabled(name):
'''
Check to see if the named service is disabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.disabled <service name>
'''
if _service_is_upstart(name):
return _upstart_is_disabled(name)
else:
if _service_is_sysv(name):
return _sysv_is_disabled(name)
return None | python | def disabled(name):
'''
Check to see if the named service is disabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.disabled <service name>
'''
if _service_is_upstart(name):
return _upstart_is_disabled(name)
else:
if _service_is_sysv(name):
return _sysv_is_disabled(name)
return None | [
"def",
"disabled",
"(",
"name",
")",
":",
"if",
"_service_is_upstart",
"(",
"name",
")",
":",
"return",
"_upstart_is_disabled",
"(",
"name",
")",
"else",
":",
"if",
"_service_is_sysv",
"(",
"name",
")",
":",
"return",
"_sysv_is_disabled",
"(",
"name",
")",
... | Check to see if the named service is disabled to start on boot
CLI Example:
.. code-block:: bash
salt '*' service.disabled <service name> | [
"Check",
"to",
"see",
"if",
"the",
"named",
"service",
"is",
"disabled",
"to",
"start",
"on",
"boot"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/upstart_service.py#L590-L605 | train |
saltstack/salt | salt/auth/yubico.py | __get_yubico_users | def __get_yubico_users(username):
'''
Grab the YubiKey Client ID & Secret Key
'''
user = {}
try:
if __opts__['yubico_users'].get(username, None):
(user['id'], user['key']) = list(__opts__['yubico_users'][username].values())
else:
return None
except KeyError:
return None
return user | python | def __get_yubico_users(username):
'''
Grab the YubiKey Client ID & Secret Key
'''
user = {}
try:
if __opts__['yubico_users'].get(username, None):
(user['id'], user['key']) = list(__opts__['yubico_users'][username].values())
else:
return None
except KeyError:
return None
return user | [
"def",
"__get_yubico_users",
"(",
"username",
")",
":",
"user",
"=",
"{",
"}",
"try",
":",
"if",
"__opts__",
"[",
"'yubico_users'",
"]",
".",
"get",
"(",
"username",
",",
"None",
")",
":",
"(",
"user",
"[",
"'id'",
"]",
",",
"user",
"[",
"'key'",
"... | Grab the YubiKey Client ID & Secret Key | [
"Grab",
"the",
"YubiKey",
"Client",
"ID",
"&",
"Secret",
"Key"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/yubico.py#L55-L69 | train |
saltstack/salt | salt/auth/yubico.py | auth | def auth(username, password):
'''
Authenticate against yubico server
'''
_cred = __get_yubico_users(username)
client = Yubico(_cred['id'], _cred['key'])
try:
return client.verify(password)
except yubico_exceptions.StatusCodeError as e:
log.info('Unable to verify YubiKey `%s`', e)
return False | python | def auth(username, password):
'''
Authenticate against yubico server
'''
_cred = __get_yubico_users(username)
client = Yubico(_cred['id'], _cred['key'])
try:
return client.verify(password)
except yubico_exceptions.StatusCodeError as e:
log.info('Unable to verify YubiKey `%s`', e)
return False | [
"def",
"auth",
"(",
"username",
",",
"password",
")",
":",
"_cred",
"=",
"__get_yubico_users",
"(",
"username",
")",
"client",
"=",
"Yubico",
"(",
"_cred",
"[",
"'id'",
"]",
",",
"_cred",
"[",
"'key'",
"]",
")",
"try",
":",
"return",
"client",
".",
"... | Authenticate against yubico server | [
"Authenticate",
"against",
"yubico",
"server"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/auth/yubico.py#L72-L84 | train |
saltstack/salt | salt/log/mixins.py | ExcInfoOnLogLevelFormatMixIn.format | def format(self, record):
'''
Format the log record to include exc_info if the handler is enabled for a specific log level
'''
formatted_record = super(ExcInfoOnLogLevelFormatMixIn, self).format(record)
exc_info_on_loglevel = getattr(record, 'exc_info_on_loglevel', None)
exc_info_on_loglevel_formatted = getattr(record, 'exc_info_on_loglevel_formatted', None)
if exc_info_on_loglevel is None and exc_info_on_loglevel_formatted is None:
return formatted_record
# If we reached this far it means the log record was created with exc_info_on_loglevel
# If this specific handler is enabled for that record, then we should format it to
# include the exc_info details
if self.level > exc_info_on_loglevel:
# This handler is not enabled for the desired exc_info_on_loglevel, don't include exc_info
return formatted_record
# If we reached this far it means we should include exc_info
if not record.exc_info_on_loglevel_instance and not exc_info_on_loglevel_formatted:
# This should actually never occur
return formatted_record
if record.exc_info_on_loglevel_formatted is None:
# Let's cache the formatted exception to avoid recurring conversions and formatting calls
if self.formatter is None: # pylint: disable=access-member-before-definition
self.formatter = logging._defaultFormatter
record.exc_info_on_loglevel_formatted = self.formatter.formatException(
record.exc_info_on_loglevel_instance
)
# Let's format the record to include exc_info just like python's logging formatted does
if formatted_record[-1:] != '\n':
formatted_record += '\n'
try:
formatted_record += record.exc_info_on_loglevel_formatted
except UnicodeError:
# According to the standard library logging formatter comments:
#
# Sometimes filenames have non-ASCII chars, which can lead
# to errors when s is Unicode and record.exc_text is str
# See issue 8924.
# We also use replace for when there are multiple
# encodings, e.g. UTF-8 for the filesystem and latin-1
# for a script. See issue 13232.
formatted_record += record.exc_info_on_loglevel_formatted.decode(sys.getfilesystemencoding(),
'replace')
# Reset the record.exc_info_on_loglevel_instance because it might need
# to "travel" through a multiprocessing process and it might contain
# data which is not pickle'able
record.exc_info_on_loglevel_instance = None
return formatted_record | python | def format(self, record):
'''
Format the log record to include exc_info if the handler is enabled for a specific log level
'''
formatted_record = super(ExcInfoOnLogLevelFormatMixIn, self).format(record)
exc_info_on_loglevel = getattr(record, 'exc_info_on_loglevel', None)
exc_info_on_loglevel_formatted = getattr(record, 'exc_info_on_loglevel_formatted', None)
if exc_info_on_loglevel is None and exc_info_on_loglevel_formatted is None:
return formatted_record
# If we reached this far it means the log record was created with exc_info_on_loglevel
# If this specific handler is enabled for that record, then we should format it to
# include the exc_info details
if self.level > exc_info_on_loglevel:
# This handler is not enabled for the desired exc_info_on_loglevel, don't include exc_info
return formatted_record
# If we reached this far it means we should include exc_info
if not record.exc_info_on_loglevel_instance and not exc_info_on_loglevel_formatted:
# This should actually never occur
return formatted_record
if record.exc_info_on_loglevel_formatted is None:
# Let's cache the formatted exception to avoid recurring conversions and formatting calls
if self.formatter is None: # pylint: disable=access-member-before-definition
self.formatter = logging._defaultFormatter
record.exc_info_on_loglevel_formatted = self.formatter.formatException(
record.exc_info_on_loglevel_instance
)
# Let's format the record to include exc_info just like python's logging formatted does
if formatted_record[-1:] != '\n':
formatted_record += '\n'
try:
formatted_record += record.exc_info_on_loglevel_formatted
except UnicodeError:
# According to the standard library logging formatter comments:
#
# Sometimes filenames have non-ASCII chars, which can lead
# to errors when s is Unicode and record.exc_text is str
# See issue 8924.
# We also use replace for when there are multiple
# encodings, e.g. UTF-8 for the filesystem and latin-1
# for a script. See issue 13232.
formatted_record += record.exc_info_on_loglevel_formatted.decode(sys.getfilesystemencoding(),
'replace')
# Reset the record.exc_info_on_loglevel_instance because it might need
# to "travel" through a multiprocessing process and it might contain
# data which is not pickle'able
record.exc_info_on_loglevel_instance = None
return formatted_record | [
"def",
"format",
"(",
"self",
",",
"record",
")",
":",
"formatted_record",
"=",
"super",
"(",
"ExcInfoOnLogLevelFormatMixIn",
",",
"self",
")",
".",
"format",
"(",
"record",
")",
"exc_info_on_loglevel",
"=",
"getattr",
"(",
"record",
",",
"'exc_info_on_loglevel'... | Format the log record to include exc_info if the handler is enabled for a specific log level | [
"Format",
"the",
"log",
"record",
"to",
"include",
"exc_info",
"if",
"the",
"handler",
"is",
"enabled",
"for",
"a",
"specific",
"log",
"level"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/log/mixins.py#L90-L141 | train |
saltstack/salt | salt/modules/s3.py | delete | def delete(bucket, path=None, action=None, key=None, keyid=None,
service_url=None, verify_ssl=None, kms_keyid=None, location=None,
role_arn=None, path_style=None, https_enable=None):
'''
Delete a bucket, or delete an object from a bucket.
CLI Example to delete a bucket::
salt myminion s3.delete mybucket
CLI Example to delete an object from a bucket::
salt myminion s3.delete mybucket remoteobject
'''
key, keyid, service_url, verify_ssl, kms_keyid, location, role_arn, path_style, https_enable = _get_key(
key,
keyid,
service_url,
verify_ssl,
kms_keyid,
location,
role_arn,
path_style,
https_enable,
)
return __utils__['s3.query'](method='DELETE',
bucket=bucket,
path=path,
action=action,
key=key,
keyid=keyid,
kms_keyid=kms_keyid,
service_url=service_url,
verify_ssl=verify_ssl,
location=location,
role_arn=role_arn,
path_style=path_style,
https_enable=https_enable) | python | def delete(bucket, path=None, action=None, key=None, keyid=None,
service_url=None, verify_ssl=None, kms_keyid=None, location=None,
role_arn=None, path_style=None, https_enable=None):
'''
Delete a bucket, or delete an object from a bucket.
CLI Example to delete a bucket::
salt myminion s3.delete mybucket
CLI Example to delete an object from a bucket::
salt myminion s3.delete mybucket remoteobject
'''
key, keyid, service_url, verify_ssl, kms_keyid, location, role_arn, path_style, https_enable = _get_key(
key,
keyid,
service_url,
verify_ssl,
kms_keyid,
location,
role_arn,
path_style,
https_enable,
)
return __utils__['s3.query'](method='DELETE',
bucket=bucket,
path=path,
action=action,
key=key,
keyid=keyid,
kms_keyid=kms_keyid,
service_url=service_url,
verify_ssl=verify_ssl,
location=location,
role_arn=role_arn,
path_style=path_style,
https_enable=https_enable) | [
"def",
"delete",
"(",
"bucket",
",",
"path",
"=",
"None",
",",
"action",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"service_url",
"=",
"None",
",",
"verify_ssl",
"=",
"None",
",",
"kms_keyid",
"=",
"None",
",",
"location",... | Delete a bucket, or delete an object from a bucket.
CLI Example to delete a bucket::
salt myminion s3.delete mybucket
CLI Example to delete an object from a bucket::
salt myminion s3.delete mybucket remoteobject | [
"Delete",
"a",
"bucket",
"or",
"delete",
"an",
"object",
"from",
"a",
"bucket",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/s3.py#L82-L120 | train |
saltstack/salt | salt/modules/s3.py | get | def get(bucket='', path='', return_bin=False, action=None,
local_file=None, key=None, keyid=None, service_url=None,
verify_ssl=None, kms_keyid=None, location=None, role_arn=None,
path_style=None, https_enable=None):
'''
List the contents of a bucket, or return an object from a bucket. Set
return_bin to True in order to retrieve an object wholesale. Otherwise,
Salt will attempt to parse an XML response.
CLI Example to list buckets:
.. code-block:: bash
salt myminion s3.get
CLI Example to list the contents of a bucket:
.. code-block:: bash
salt myminion s3.get mybucket
CLI Example to return the binary contents of an object:
.. code-block:: bash
salt myminion s3.get mybucket myfile.png return_bin=True
CLI Example to save the binary contents of an object to a local file:
.. code-block:: bash
salt myminion s3.get mybucket myfile.png local_file=/tmp/myfile.png
It is also possible to perform an action on a bucket. Currently, S3
supports the following actions::
acl
cors
lifecycle
policy
location
logging
notification
tagging
versions
requestPayment
versioning
website
To perform an action on a bucket:
.. code-block:: bash
salt myminion s3.get mybucket myfile.png action=acl
'''
key, keyid, service_url, verify_ssl, kms_keyid, location, role_arn, path_style, https_enable = _get_key(
key,
keyid,
service_url,
verify_ssl,
kms_keyid,
location,
role_arn,
path_style,
https_enable,
)
return __utils__['s3.query'](method='GET',
bucket=bucket,
path=path,
return_bin=return_bin,
local_file=local_file,
action=action,
key=key,
keyid=keyid,
kms_keyid=kms_keyid,
service_url=service_url,
verify_ssl=verify_ssl,
location=location,
role_arn=role_arn,
path_style=path_style,
https_enable=https_enable) | python | def get(bucket='', path='', return_bin=False, action=None,
local_file=None, key=None, keyid=None, service_url=None,
verify_ssl=None, kms_keyid=None, location=None, role_arn=None,
path_style=None, https_enable=None):
'''
List the contents of a bucket, or return an object from a bucket. Set
return_bin to True in order to retrieve an object wholesale. Otherwise,
Salt will attempt to parse an XML response.
CLI Example to list buckets:
.. code-block:: bash
salt myminion s3.get
CLI Example to list the contents of a bucket:
.. code-block:: bash
salt myminion s3.get mybucket
CLI Example to return the binary contents of an object:
.. code-block:: bash
salt myminion s3.get mybucket myfile.png return_bin=True
CLI Example to save the binary contents of an object to a local file:
.. code-block:: bash
salt myminion s3.get mybucket myfile.png local_file=/tmp/myfile.png
It is also possible to perform an action on a bucket. Currently, S3
supports the following actions::
acl
cors
lifecycle
policy
location
logging
notification
tagging
versions
requestPayment
versioning
website
To perform an action on a bucket:
.. code-block:: bash
salt myminion s3.get mybucket myfile.png action=acl
'''
key, keyid, service_url, verify_ssl, kms_keyid, location, role_arn, path_style, https_enable = _get_key(
key,
keyid,
service_url,
verify_ssl,
kms_keyid,
location,
role_arn,
path_style,
https_enable,
)
return __utils__['s3.query'](method='GET',
bucket=bucket,
path=path,
return_bin=return_bin,
local_file=local_file,
action=action,
key=key,
keyid=keyid,
kms_keyid=kms_keyid,
service_url=service_url,
verify_ssl=verify_ssl,
location=location,
role_arn=role_arn,
path_style=path_style,
https_enable=https_enable) | [
"def",
"get",
"(",
"bucket",
"=",
"''",
",",
"path",
"=",
"''",
",",
"return_bin",
"=",
"False",
",",
"action",
"=",
"None",
",",
"local_file",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"service_url",
"=",
"None",
",",
... | List the contents of a bucket, or return an object from a bucket. Set
return_bin to True in order to retrieve an object wholesale. Otherwise,
Salt will attempt to parse an XML response.
CLI Example to list buckets:
.. code-block:: bash
salt myminion s3.get
CLI Example to list the contents of a bucket:
.. code-block:: bash
salt myminion s3.get mybucket
CLI Example to return the binary contents of an object:
.. code-block:: bash
salt myminion s3.get mybucket myfile.png return_bin=True
CLI Example to save the binary contents of an object to a local file:
.. code-block:: bash
salt myminion s3.get mybucket myfile.png local_file=/tmp/myfile.png
It is also possible to perform an action on a bucket. Currently, S3
supports the following actions::
acl
cors
lifecycle
policy
location
logging
notification
tagging
versions
requestPayment
versioning
website
To perform an action on a bucket:
.. code-block:: bash
salt myminion s3.get mybucket myfile.png action=acl | [
"List",
"the",
"contents",
"of",
"a",
"bucket",
"or",
"return",
"an",
"object",
"from",
"a",
"bucket",
".",
"Set",
"return_bin",
"to",
"True",
"in",
"order",
"to",
"retrieve",
"an",
"object",
"wholesale",
".",
"Otherwise",
"Salt",
"will",
"attempt",
"to",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/s3.py#L123-L204 | train |
saltstack/salt | salt/modules/s3.py | head | def head(bucket, path='', key=None, keyid=None, service_url=None,
verify_ssl=None, kms_keyid=None, location=None, role_arn=None,
path_style=None, https_enable=None):
'''
Return the metadata for a bucket, or an object in a bucket.
CLI Examples:
.. code-block:: bash
salt myminion s3.head mybucket
salt myminion s3.head mybucket myfile.png
'''
key, keyid, service_url, verify_ssl, kms_keyid, location, role_arn, path_style, https_enable = _get_key(
key,
keyid,
service_url,
verify_ssl,
kms_keyid,
location,
role_arn,
path_style,
https_enable,
)
return __utils__['s3.query'](method='HEAD',
bucket=bucket,
path=path,
key=key,
keyid=keyid,
kms_keyid=kms_keyid,
service_url=service_url,
verify_ssl=verify_ssl,
location=location,
full_headers=True,
role_arn=role_arn,
path_style=path_style,
https_enable=https_enable) | python | def head(bucket, path='', key=None, keyid=None, service_url=None,
verify_ssl=None, kms_keyid=None, location=None, role_arn=None,
path_style=None, https_enable=None):
'''
Return the metadata for a bucket, or an object in a bucket.
CLI Examples:
.. code-block:: bash
salt myminion s3.head mybucket
salt myminion s3.head mybucket myfile.png
'''
key, keyid, service_url, verify_ssl, kms_keyid, location, role_arn, path_style, https_enable = _get_key(
key,
keyid,
service_url,
verify_ssl,
kms_keyid,
location,
role_arn,
path_style,
https_enable,
)
return __utils__['s3.query'](method='HEAD',
bucket=bucket,
path=path,
key=key,
keyid=keyid,
kms_keyid=kms_keyid,
service_url=service_url,
verify_ssl=verify_ssl,
location=location,
full_headers=True,
role_arn=role_arn,
path_style=path_style,
https_enable=https_enable) | [
"def",
"head",
"(",
"bucket",
",",
"path",
"=",
"''",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"service_url",
"=",
"None",
",",
"verify_ssl",
"=",
"None",
",",
"kms_keyid",
"=",
"None",
",",
"location",
"=",
"None",
",",
"role_arn",
... | Return the metadata for a bucket, or an object in a bucket.
CLI Examples:
.. code-block:: bash
salt myminion s3.head mybucket
salt myminion s3.head mybucket myfile.png | [
"Return",
"the",
"metadata",
"for",
"a",
"bucket",
"or",
"an",
"object",
"in",
"a",
"bucket",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/s3.py#L207-L244 | train |
saltstack/salt | salt/modules/s3.py | put | def put(bucket, path=None, return_bin=False, action=None, local_file=None,
key=None, keyid=None, service_url=None, verify_ssl=None,
kms_keyid=None, location=None, role_arn=None, path_style=None,
https_enable=None, headers=None, full_headers=False):
'''
Create a new bucket, or upload an object to a bucket.
CLI Example to create a bucket:
.. code-block:: bash
salt myminion s3.put mybucket
CLI Example to upload an object to a bucket:
.. code-block:: bash
salt myminion s3.put mybucket remotepath local_file=/path/to/file
'''
if not headers:
headers = {}
else:
full_headers = True
key, keyid, service_url, verify_ssl, kms_keyid, location, role_arn, path_style, https_enable = _get_key(
key,
keyid,
service_url,
verify_ssl,
kms_keyid,
location,
role_arn,
path_style,
https_enable,
)
return __utils__['s3.query'](method='PUT',
bucket=bucket,
path=path,
return_bin=return_bin,
local_file=local_file,
action=action,
key=key,
keyid=keyid,
kms_keyid=kms_keyid,
service_url=service_url,
verify_ssl=verify_ssl,
location=location,
role_arn=role_arn,
path_style=path_style,
https_enable=https_enable,
headers=headers,
full_headers=full_headers) | python | def put(bucket, path=None, return_bin=False, action=None, local_file=None,
key=None, keyid=None, service_url=None, verify_ssl=None,
kms_keyid=None, location=None, role_arn=None, path_style=None,
https_enable=None, headers=None, full_headers=False):
'''
Create a new bucket, or upload an object to a bucket.
CLI Example to create a bucket:
.. code-block:: bash
salt myminion s3.put mybucket
CLI Example to upload an object to a bucket:
.. code-block:: bash
salt myminion s3.put mybucket remotepath local_file=/path/to/file
'''
if not headers:
headers = {}
else:
full_headers = True
key, keyid, service_url, verify_ssl, kms_keyid, location, role_arn, path_style, https_enable = _get_key(
key,
keyid,
service_url,
verify_ssl,
kms_keyid,
location,
role_arn,
path_style,
https_enable,
)
return __utils__['s3.query'](method='PUT',
bucket=bucket,
path=path,
return_bin=return_bin,
local_file=local_file,
action=action,
key=key,
keyid=keyid,
kms_keyid=kms_keyid,
service_url=service_url,
verify_ssl=verify_ssl,
location=location,
role_arn=role_arn,
path_style=path_style,
https_enable=https_enable,
headers=headers,
full_headers=full_headers) | [
"def",
"put",
"(",
"bucket",
",",
"path",
"=",
"None",
",",
"return_bin",
"=",
"False",
",",
"action",
"=",
"None",
",",
"local_file",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"service_url",
"=",
"None",
",",
"verify_ssl"... | Create a new bucket, or upload an object to a bucket.
CLI Example to create a bucket:
.. code-block:: bash
salt myminion s3.put mybucket
CLI Example to upload an object to a bucket:
.. code-block:: bash
salt myminion s3.put mybucket remotepath local_file=/path/to/file | [
"Create",
"a",
"new",
"bucket",
"or",
"upload",
"an",
"object",
"to",
"a",
"bucket",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/s3.py#L247-L300 | train |
saltstack/salt | salt/modules/s3.py | _get_key | def _get_key(key, keyid, service_url, verify_ssl, kms_keyid, location, role_arn, path_style, https_enable):
'''
Examine the keys, and populate as necessary
'''
if not key and __salt__['config.option']('s3.key'):
key = __salt__['config.option']('s3.key')
if not keyid and __salt__['config.option']('s3.keyid'):
keyid = __salt__['config.option']('s3.keyid')
if not kms_keyid and __salt__['config.option']('aws.kms.keyid'):
kms_keyid = __salt__['config.option']('aws.kms.keyid')
if not service_url and __salt__['config.option']('s3.service_url'):
service_url = __salt__['config.option']('s3.service_url')
if not service_url:
service_url = 's3.amazonaws.com'
if verify_ssl is None and __salt__['config.option']('s3.verify_ssl') is not None:
verify_ssl = __salt__['config.option']('s3.verify_ssl')
if verify_ssl is None:
verify_ssl = True
if location is None and __salt__['config.option']('s3.location') is not None:
location = __salt__['config.option']('s3.location')
if role_arn is None and __salt__['config.option']('s3.role_arn'):
role_arn = __salt__['config.option']('s3.role_arn')
if path_style is None and __salt__['config.option']('s3.path_style') is not None:
path_style = __salt__['config.option']('s3.path_style')
if path_style is None:
path_style = False
if https_enable is None and __salt__['config.option']('s3.https_enable') is not None:
https_enable = __salt__['config.option']('s3.https_enable')
if https_enable is None:
https_enable = True
return key, keyid, service_url, verify_ssl, kms_keyid, location, role_arn, path_style, https_enable | python | def _get_key(key, keyid, service_url, verify_ssl, kms_keyid, location, role_arn, path_style, https_enable):
'''
Examine the keys, and populate as necessary
'''
if not key and __salt__['config.option']('s3.key'):
key = __salt__['config.option']('s3.key')
if not keyid and __salt__['config.option']('s3.keyid'):
keyid = __salt__['config.option']('s3.keyid')
if not kms_keyid and __salt__['config.option']('aws.kms.keyid'):
kms_keyid = __salt__['config.option']('aws.kms.keyid')
if not service_url and __salt__['config.option']('s3.service_url'):
service_url = __salt__['config.option']('s3.service_url')
if not service_url:
service_url = 's3.amazonaws.com'
if verify_ssl is None and __salt__['config.option']('s3.verify_ssl') is not None:
verify_ssl = __salt__['config.option']('s3.verify_ssl')
if verify_ssl is None:
verify_ssl = True
if location is None and __salt__['config.option']('s3.location') is not None:
location = __salt__['config.option']('s3.location')
if role_arn is None and __salt__['config.option']('s3.role_arn'):
role_arn = __salt__['config.option']('s3.role_arn')
if path_style is None and __salt__['config.option']('s3.path_style') is not None:
path_style = __salt__['config.option']('s3.path_style')
if path_style is None:
path_style = False
if https_enable is None and __salt__['config.option']('s3.https_enable') is not None:
https_enable = __salt__['config.option']('s3.https_enable')
if https_enable is None:
https_enable = True
return key, keyid, service_url, verify_ssl, kms_keyid, location, role_arn, path_style, https_enable | [
"def",
"_get_key",
"(",
"key",
",",
"keyid",
",",
"service_url",
",",
"verify_ssl",
",",
"kms_keyid",
",",
"location",
",",
"role_arn",
",",
"path_style",
",",
"https_enable",
")",
":",
"if",
"not",
"key",
"and",
"__salt__",
"[",
"'config.option'",
"]",
"(... | Examine the keys, and populate as necessary | [
"Examine",
"the",
"keys",
"and",
"populate",
"as",
"necessary"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/s3.py#L303-L346 | train |
saltstack/salt | salt/modules/pdbedit.py | generate_nt_hash | def generate_nt_hash(password):
'''
Generate a NT HASH
CLI Example:
.. code-block:: bash
salt '*' pdbedit.generate_nt_hash my_passwd
'''
return binascii.hexlify(
hashlib.new(
'md4',
password.encode('utf-16le')
).digest()
).upper() | python | def generate_nt_hash(password):
'''
Generate a NT HASH
CLI Example:
.. code-block:: bash
salt '*' pdbedit.generate_nt_hash my_passwd
'''
return binascii.hexlify(
hashlib.new(
'md4',
password.encode('utf-16le')
).digest()
).upper() | [
"def",
"generate_nt_hash",
"(",
"password",
")",
":",
"return",
"binascii",
".",
"hexlify",
"(",
"hashlib",
".",
"new",
"(",
"'md4'",
",",
"password",
".",
"encode",
"(",
"'utf-16le'",
")",
")",
".",
"digest",
"(",
")",
")",
".",
"upper",
"(",
")"
] | Generate a NT HASH
CLI Example:
.. code-block:: bash
salt '*' pdbedit.generate_nt_hash my_passwd | [
"Generate",
"a",
"NT",
"HASH"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pdbedit.py#L52-L67 | train |
saltstack/salt | salt/modules/pdbedit.py | list_users | def list_users(verbose=True, hashes=False):
'''
List user accounts
verbose : boolean
return all information
hashes : boolean
include NT HASH and LM HASH in verbose output
CLI Example:
.. code-block:: bash
salt '*' pdbedit.list
'''
users = {} if verbose else []
if verbose:
# parse detailed user data
res = __salt__['cmd.run_all'](
'pdbedit --list --verbose {hashes}'.format(hashes="--smbpasswd-style" if hashes else ""),
)
if res['retcode'] > 0:
log.error(res['stderr'] if 'stderr' in res else res['stdout'])
return users
user_data = {}
for user in res['stdout'].splitlines():
if user.startswith('-'):
if 'unix username' in user_data:
users[user_data['unix username']] = user_data
user_data = {}
elif ':' in user:
label = user[:user.index(':')].strip().lower()
data = user[(user.index(':')+1):].strip()
user_data[label] = data
if user_data:
users[user_data['unix username']] = user_data
else:
# list users
res = __salt__['cmd.run_all']('pdbedit --list')
if res['retcode'] > 0:
return {'Error': res['stderr'] if 'stderr' in res else res['stdout']}
for user in res['stdout'].splitlines():
if ':' not in user:
continue
user_data = user.split(':')
if len(user_data) >= 3:
users.append(user_data[0])
return users | python | def list_users(verbose=True, hashes=False):
'''
List user accounts
verbose : boolean
return all information
hashes : boolean
include NT HASH and LM HASH in verbose output
CLI Example:
.. code-block:: bash
salt '*' pdbedit.list
'''
users = {} if verbose else []
if verbose:
# parse detailed user data
res = __salt__['cmd.run_all'](
'pdbedit --list --verbose {hashes}'.format(hashes="--smbpasswd-style" if hashes else ""),
)
if res['retcode'] > 0:
log.error(res['stderr'] if 'stderr' in res else res['stdout'])
return users
user_data = {}
for user in res['stdout'].splitlines():
if user.startswith('-'):
if 'unix username' in user_data:
users[user_data['unix username']] = user_data
user_data = {}
elif ':' in user:
label = user[:user.index(':')].strip().lower()
data = user[(user.index(':')+1):].strip()
user_data[label] = data
if user_data:
users[user_data['unix username']] = user_data
else:
# list users
res = __salt__['cmd.run_all']('pdbedit --list')
if res['retcode'] > 0:
return {'Error': res['stderr'] if 'stderr' in res else res['stdout']}
for user in res['stdout'].splitlines():
if ':' not in user:
continue
user_data = user.split(':')
if len(user_data) >= 3:
users.append(user_data[0])
return users | [
"def",
"list_users",
"(",
"verbose",
"=",
"True",
",",
"hashes",
"=",
"False",
")",
":",
"users",
"=",
"{",
"}",
"if",
"verbose",
"else",
"[",
"]",
"if",
"verbose",
":",
"# parse detailed user data",
"res",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"("... | List user accounts
verbose : boolean
return all information
hashes : boolean
include NT HASH and LM HASH in verbose output
CLI Example:
.. code-block:: bash
salt '*' pdbedit.list | [
"List",
"user",
"accounts"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pdbedit.py#L70-L124 | train |
saltstack/salt | salt/modules/pdbedit.py | get_user | def get_user(login, hashes=False):
'''
Get user account details
login : string
login name
hashes : boolean
include NTHASH and LMHASH in verbose output
CLI Example:
.. code-block:: bash
salt '*' pdbedit.get kaylee
'''
users = list_users(verbose=True, hashes=hashes)
return users[login] if login in users else {} | python | def get_user(login, hashes=False):
'''
Get user account details
login : string
login name
hashes : boolean
include NTHASH and LMHASH in verbose output
CLI Example:
.. code-block:: bash
salt '*' pdbedit.get kaylee
'''
users = list_users(verbose=True, hashes=hashes)
return users[login] if login in users else {} | [
"def",
"get_user",
"(",
"login",
",",
"hashes",
"=",
"False",
")",
":",
"users",
"=",
"list_users",
"(",
"verbose",
"=",
"True",
",",
"hashes",
"=",
"hashes",
")",
"return",
"users",
"[",
"login",
"]",
"if",
"login",
"in",
"users",
"else",
"{",
"}"
] | Get user account details
login : string
login name
hashes : boolean
include NTHASH and LMHASH in verbose output
CLI Example:
.. code-block:: bash
salt '*' pdbedit.get kaylee | [
"Get",
"user",
"account",
"details"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pdbedit.py#L127-L143 | train |
saltstack/salt | salt/modules/pdbedit.py | delete | def delete(login):
'''
Delete user account
login : string
login name
CLI Example:
.. code-block:: bash
salt '*' pdbedit.delete wash
'''
if login in list_users(False):
res = __salt__['cmd.run_all'](
'pdbedit --delete {login}'.format(login=_quote_args(login)),
)
if res['retcode'] > 0:
return {login: res['stderr'] if 'stderr' in res else res['stdout']}
return {login: 'deleted'}
return {login: 'absent'} | python | def delete(login):
'''
Delete user account
login : string
login name
CLI Example:
.. code-block:: bash
salt '*' pdbedit.delete wash
'''
if login in list_users(False):
res = __salt__['cmd.run_all'](
'pdbedit --delete {login}'.format(login=_quote_args(login)),
)
if res['retcode'] > 0:
return {login: res['stderr'] if 'stderr' in res else res['stdout']}
return {login: 'deleted'}
return {login: 'absent'} | [
"def",
"delete",
"(",
"login",
")",
":",
"if",
"login",
"in",
"list_users",
"(",
"False",
")",
":",
"res",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"'pdbedit --delete {login}'",
".",
"format",
"(",
"login",
"=",
"_quote_args",
"(",
"login",
")",
... | Delete user account
login : string
login name
CLI Example:
.. code-block:: bash
salt '*' pdbedit.delete wash | [
"Delete",
"user",
"account"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pdbedit.py#L146-L169 | train |
saltstack/salt | salt/modules/pdbedit.py | create | def create(login, password, password_hashed=False, machine_account=False):
'''
Create user account
login : string
login name
password : string
password
password_hashed : boolean
set if password is a nt hash instead of plain text
machine_account : boolean
set to create a machine trust account instead
CLI Example:
.. code-block:: bash
salt '*' pdbedit.create zoe 9764951149F84E770889011E1DC4A927 nthash
salt '*' pdbedit.create river 1sw4ll0w3d4bug
'''
ret = 'unchanged'
# generate nt hash if needed
if password_hashed:
password_hash = password.upper()
password = "" # wipe password
else:
password_hash = generate_nt_hash(password)
# create user
if login not in list_users(False):
# NOTE: --create requires a password, even if blank
res = __salt__['cmd.run_all'](
cmd='pdbedit --create --user {login} -t {machine}'.format(
login=_quote_args(login),
machine="--machine" if machine_account else "",
),
stdin="{password}\n{password}\n".format(password=password),
)
if res['retcode'] > 0:
return {login: res['stderr'] if 'stderr' in res else res['stdout']}
ret = 'created'
# update password if needed
user = get_user(login, True)
if user['nt hash'] != password_hash:
res = __salt__['cmd.run_all'](
'pdbedit --modify --user {login} --set-nt-hash={nthash}'.format(
login=_quote_args(login),
nthash=_quote_args(password_hash)
),
)
if res['retcode'] > 0:
return {login: res['stderr'] if 'stderr' in res else res['stdout']}
if ret != 'created':
ret = 'updated'
return {login: ret} | python | def create(login, password, password_hashed=False, machine_account=False):
'''
Create user account
login : string
login name
password : string
password
password_hashed : boolean
set if password is a nt hash instead of plain text
machine_account : boolean
set to create a machine trust account instead
CLI Example:
.. code-block:: bash
salt '*' pdbedit.create zoe 9764951149F84E770889011E1DC4A927 nthash
salt '*' pdbedit.create river 1sw4ll0w3d4bug
'''
ret = 'unchanged'
# generate nt hash if needed
if password_hashed:
password_hash = password.upper()
password = "" # wipe password
else:
password_hash = generate_nt_hash(password)
# create user
if login not in list_users(False):
# NOTE: --create requires a password, even if blank
res = __salt__['cmd.run_all'](
cmd='pdbedit --create --user {login} -t {machine}'.format(
login=_quote_args(login),
machine="--machine" if machine_account else "",
),
stdin="{password}\n{password}\n".format(password=password),
)
if res['retcode'] > 0:
return {login: res['stderr'] if 'stderr' in res else res['stdout']}
ret = 'created'
# update password if needed
user = get_user(login, True)
if user['nt hash'] != password_hash:
res = __salt__['cmd.run_all'](
'pdbedit --modify --user {login} --set-nt-hash={nthash}'.format(
login=_quote_args(login),
nthash=_quote_args(password_hash)
),
)
if res['retcode'] > 0:
return {login: res['stderr'] if 'stderr' in res else res['stdout']}
if ret != 'created':
ret = 'updated'
return {login: ret} | [
"def",
"create",
"(",
"login",
",",
"password",
",",
"password_hashed",
"=",
"False",
",",
"machine_account",
"=",
"False",
")",
":",
"ret",
"=",
"'unchanged'",
"# generate nt hash if needed",
"if",
"password_hashed",
":",
"password_hash",
"=",
"password",
".",
... | Create user account
login : string
login name
password : string
password
password_hashed : boolean
set if password is a nt hash instead of plain text
machine_account : boolean
set to create a machine trust account instead
CLI Example:
.. code-block:: bash
salt '*' pdbedit.create zoe 9764951149F84E770889011E1DC4A927 nthash
salt '*' pdbedit.create river 1sw4ll0w3d4bug | [
"Create",
"user",
"account"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pdbedit.py#L172-L233 | train |
saltstack/salt | salt/modules/pdbedit.py | modify | def modify(
login, password=None, password_hashed=False,
domain=None, profile=None, script=None,
drive=None, homedir=None, fullname=None,
account_desc=None, account_control=None,
machine_sid=None, user_sid=None,
reset_login_hours=False, reset_bad_password_count=False,
):
'''
Modify user account
login : string
login name
password : string
password
password_hashed : boolean
set if password is a nt hash instead of plain text
domain : string
users domain
profile : string
profile path
script : string
logon script
drive : string
home drive
homedir : string
home directory
fullname : string
full name
account_desc : string
account description
machine_sid : string
specify the machines new primary group SID or rid
user_sid : string
specify the users new primary group SID or rid
account_control : string
specify user account control properties
.. note::
Only the following can be set:
- N: No password required
- D: Account disabled
- H: Home directory required
- L: Automatic Locking
- X: Password does not expire
reset_login_hours : boolean
reset the users allowed logon hours
reset_bad_password_count : boolean
reset the stored bad login counter
.. note::
if user is absent and password is provided, the user will be created
CLI Example:
.. code-block:: bash
salt '*' pdbedit.modify inara fullname='Inara Serra'
salt '*' pdbedit.modify simon password=r1v3r
salt '*' pdbedit.modify jane drive='V:' homedir='\\\\serenity\\jane\\profile'
salt '*' pdbedit.modify mal account_control=NX
'''
ret = 'unchanged'
# flag mapping
flags = {
'domain': '--domain=',
'full name': '--fullname=',
'account desc': '--account-desc=',
'home directory': '--homedir=',
'homedir drive': '--drive=',
'profile path': '--profile=',
'logon script': '--script=',
'account flags': '--account-control=',
'user sid': '-U ',
'machine sid': '-M ',
}
# field mapping
provided = {
'domain': domain,
'full name': fullname,
'account desc': account_desc,
'home directory': homedir,
'homedir drive': drive,
'profile path': profile,
'logon script': script,
'account flags': account_control,
'user sid': user_sid,
'machine sid': machine_sid,
}
# update password
if password:
ret = create(login, password, password_hashed)[login]
if ret not in ['updated', 'created', 'unchanged']:
return {login: ret}
elif login not in list_users(False):
return {login: 'absent'}
# check for changes
current = get_user(login, hashes=True)
changes = {}
for key, val in provided.items():
if key in ['user sid', 'machine sid']:
if val is not None and key in current and not current[key].endswith(six.text_type(val)):
changes[key] = six.text_type(val)
elif key in ['account flags']:
if val is not None:
if val.startswith('['):
val = val[1:-1]
new = []
for f in val.upper():
if f not in ['N', 'D', 'H', 'L', 'X']:
logmsg = 'pdbedit.modify - unknown {} flag for account_control, ignored'.format(f)
log.warning(logmsg)
else:
new.append(f)
changes[key] = "[{flags}]".format(flags="".join(new))
else:
if val is not None and key in current and current[key] != val:
changes[key] = val
# apply changes
if changes or reset_login_hours or reset_bad_password_count:
cmds = []
for change in changes:
cmds.append('{flag}{value}'.format(
flag=flags[change],
value=_quote_args(changes[change]),
))
if reset_login_hours:
cmds.append('--logon-hours-reset')
if reset_bad_password_count:
cmds.append('--bad-password-count-reset')
res = __salt__['cmd.run_all'](
'pdbedit --modify --user {login} {changes}'.format(
login=_quote_args(login),
changes=" ".join(cmds),
),
)
if res['retcode'] > 0:
return {login: res['stderr'] if 'stderr' in res else res['stdout']}
if ret != 'created':
ret = 'updated'
return {login: ret} | python | def modify(
login, password=None, password_hashed=False,
domain=None, profile=None, script=None,
drive=None, homedir=None, fullname=None,
account_desc=None, account_control=None,
machine_sid=None, user_sid=None,
reset_login_hours=False, reset_bad_password_count=False,
):
'''
Modify user account
login : string
login name
password : string
password
password_hashed : boolean
set if password is a nt hash instead of plain text
domain : string
users domain
profile : string
profile path
script : string
logon script
drive : string
home drive
homedir : string
home directory
fullname : string
full name
account_desc : string
account description
machine_sid : string
specify the machines new primary group SID or rid
user_sid : string
specify the users new primary group SID or rid
account_control : string
specify user account control properties
.. note::
Only the following can be set:
- N: No password required
- D: Account disabled
- H: Home directory required
- L: Automatic Locking
- X: Password does not expire
reset_login_hours : boolean
reset the users allowed logon hours
reset_bad_password_count : boolean
reset the stored bad login counter
.. note::
if user is absent and password is provided, the user will be created
CLI Example:
.. code-block:: bash
salt '*' pdbedit.modify inara fullname='Inara Serra'
salt '*' pdbedit.modify simon password=r1v3r
salt '*' pdbedit.modify jane drive='V:' homedir='\\\\serenity\\jane\\profile'
salt '*' pdbedit.modify mal account_control=NX
'''
ret = 'unchanged'
# flag mapping
flags = {
'domain': '--domain=',
'full name': '--fullname=',
'account desc': '--account-desc=',
'home directory': '--homedir=',
'homedir drive': '--drive=',
'profile path': '--profile=',
'logon script': '--script=',
'account flags': '--account-control=',
'user sid': '-U ',
'machine sid': '-M ',
}
# field mapping
provided = {
'domain': domain,
'full name': fullname,
'account desc': account_desc,
'home directory': homedir,
'homedir drive': drive,
'profile path': profile,
'logon script': script,
'account flags': account_control,
'user sid': user_sid,
'machine sid': machine_sid,
}
# update password
if password:
ret = create(login, password, password_hashed)[login]
if ret not in ['updated', 'created', 'unchanged']:
return {login: ret}
elif login not in list_users(False):
return {login: 'absent'}
# check for changes
current = get_user(login, hashes=True)
changes = {}
for key, val in provided.items():
if key in ['user sid', 'machine sid']:
if val is not None and key in current and not current[key].endswith(six.text_type(val)):
changes[key] = six.text_type(val)
elif key in ['account flags']:
if val is not None:
if val.startswith('['):
val = val[1:-1]
new = []
for f in val.upper():
if f not in ['N', 'D', 'H', 'L', 'X']:
logmsg = 'pdbedit.modify - unknown {} flag for account_control, ignored'.format(f)
log.warning(logmsg)
else:
new.append(f)
changes[key] = "[{flags}]".format(flags="".join(new))
else:
if val is not None and key in current and current[key] != val:
changes[key] = val
# apply changes
if changes or reset_login_hours or reset_bad_password_count:
cmds = []
for change in changes:
cmds.append('{flag}{value}'.format(
flag=flags[change],
value=_quote_args(changes[change]),
))
if reset_login_hours:
cmds.append('--logon-hours-reset')
if reset_bad_password_count:
cmds.append('--bad-password-count-reset')
res = __salt__['cmd.run_all'](
'pdbedit --modify --user {login} {changes}'.format(
login=_quote_args(login),
changes=" ".join(cmds),
),
)
if res['retcode'] > 0:
return {login: res['stderr'] if 'stderr' in res else res['stdout']}
if ret != 'created':
ret = 'updated'
return {login: ret} | [
"def",
"modify",
"(",
"login",
",",
"password",
"=",
"None",
",",
"password_hashed",
"=",
"False",
",",
"domain",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"script",
"=",
"None",
",",
"drive",
"=",
"None",
",",
"homedir",
"=",
"None",
",",
"full... | Modify user account
login : string
login name
password : string
password
password_hashed : boolean
set if password is a nt hash instead of plain text
domain : string
users domain
profile : string
profile path
script : string
logon script
drive : string
home drive
homedir : string
home directory
fullname : string
full name
account_desc : string
account description
machine_sid : string
specify the machines new primary group SID or rid
user_sid : string
specify the users new primary group SID or rid
account_control : string
specify user account control properties
.. note::
Only the following can be set:
- N: No password required
- D: Account disabled
- H: Home directory required
- L: Automatic Locking
- X: Password does not expire
reset_login_hours : boolean
reset the users allowed logon hours
reset_bad_password_count : boolean
reset the stored bad login counter
.. note::
if user is absent and password is provided, the user will be created
CLI Example:
.. code-block:: bash
salt '*' pdbedit.modify inara fullname='Inara Serra'
salt '*' pdbedit.modify simon password=r1v3r
salt '*' pdbedit.modify jane drive='V:' homedir='\\\\serenity\\jane\\profile'
salt '*' pdbedit.modify mal account_control=NX | [
"Modify",
"user",
"account"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pdbedit.py#L236-L385 | train |
saltstack/salt | salt/beacons/wtmp.py | _validate_time_range | def _validate_time_range(trange, status, msg):
'''
Check time range
'''
# If trange is empty, just return the current status & msg
if not trange:
return status, msg
if not isinstance(trange, dict):
status = False
msg = ('The time_range parameter for '
'wtmp beacon must '
'be a dictionary.')
if not all(k in trange for k in ('start', 'end')):
status = False
msg = ('The time_range parameter for '
'wtmp beacon must contain '
'start & end options.')
return status, msg | python | def _validate_time_range(trange, status, msg):
'''
Check time range
'''
# If trange is empty, just return the current status & msg
if not trange:
return status, msg
if not isinstance(trange, dict):
status = False
msg = ('The time_range parameter for '
'wtmp beacon must '
'be a dictionary.')
if not all(k in trange for k in ('start', 'end')):
status = False
msg = ('The time_range parameter for '
'wtmp beacon must contain '
'start & end options.')
return status, msg | [
"def",
"_validate_time_range",
"(",
"trange",
",",
"status",
",",
"msg",
")",
":",
"# If trange is empty, just return the current status & msg",
"if",
"not",
"trange",
":",
"return",
"status",
",",
"msg",
"if",
"not",
"isinstance",
"(",
"trange",
",",
"dict",
")",... | Check time range | [
"Check",
"time",
"range"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/wtmp.py#L174-L194 | train |
saltstack/salt | salt/beacons/wtmp.py | validate | def validate(config):
'''
Validate the beacon configuration
'''
vstatus = True
vmsg = 'Valid beacon configuration'
# Configuration for wtmp beacon should be a list of dicts
if not isinstance(config, list):
vstatus = False
vmsg = ('Configuration for wtmp beacon must be a list.')
else:
_config = {}
list(map(_config.update, config))
if 'users' in _config:
if not isinstance(_config['users'], dict):
vstatus = False
vmsg = ('User configuration for wtmp beacon must '
'be a dictionary.')
else:
for user in _config['users']:
_time_range = _config['users'][user].get('time_range', {})
vstatus, vmsg = _validate_time_range(_time_range,
vstatus,
vmsg)
if not vstatus:
return vstatus, vmsg
if 'groups' in _config:
if not isinstance(_config['groups'], dict):
vstatus = False
vmsg = ('Group configuration for wtmp beacon must '
'be a dictionary.')
else:
for group in _config['groups']:
_time_range = _config['groups'][group].get('time_range', {})
vstatus, vmsg = _validate_time_range(_time_range,
vstatus,
vmsg)
if not vstatus:
return vstatus, vmsg
if 'defaults' in _config:
if not isinstance(_config['defaults'], dict):
vstatus = False
vmsg = ('Defaults configuration for wtmp beacon must '
'be a dictionary.')
else:
_time_range = _config['defaults'].get('time_range', {})
vstatus, vmsg = _validate_time_range(_time_range,
vstatus,
vmsg)
if not vstatus:
return vstatus, vmsg
return vstatus, vmsg | python | def validate(config):
'''
Validate the beacon configuration
'''
vstatus = True
vmsg = 'Valid beacon configuration'
# Configuration for wtmp beacon should be a list of dicts
if not isinstance(config, list):
vstatus = False
vmsg = ('Configuration for wtmp beacon must be a list.')
else:
_config = {}
list(map(_config.update, config))
if 'users' in _config:
if not isinstance(_config['users'], dict):
vstatus = False
vmsg = ('User configuration for wtmp beacon must '
'be a dictionary.')
else:
for user in _config['users']:
_time_range = _config['users'][user].get('time_range', {})
vstatus, vmsg = _validate_time_range(_time_range,
vstatus,
vmsg)
if not vstatus:
return vstatus, vmsg
if 'groups' in _config:
if not isinstance(_config['groups'], dict):
vstatus = False
vmsg = ('Group configuration for wtmp beacon must '
'be a dictionary.')
else:
for group in _config['groups']:
_time_range = _config['groups'][group].get('time_range', {})
vstatus, vmsg = _validate_time_range(_time_range,
vstatus,
vmsg)
if not vstatus:
return vstatus, vmsg
if 'defaults' in _config:
if not isinstance(_config['defaults'], dict):
vstatus = False
vmsg = ('Defaults configuration for wtmp beacon must '
'be a dictionary.')
else:
_time_range = _config['defaults'].get('time_range', {})
vstatus, vmsg = _validate_time_range(_time_range,
vstatus,
vmsg)
if not vstatus:
return vstatus, vmsg
return vstatus, vmsg | [
"def",
"validate",
"(",
"config",
")",
":",
"vstatus",
"=",
"True",
"vmsg",
"=",
"'Valid beacon configuration'",
"# Configuration for wtmp beacon should be a list of dicts",
"if",
"not",
"isinstance",
"(",
"config",
",",
"list",
")",
":",
"vstatus",
"=",
"False",
"v... | Validate the beacon configuration | [
"Validate",
"the",
"beacon",
"configuration"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/wtmp.py#L234-L291 | train |
saltstack/salt | salt/states/supervisord.py | running | def running(name,
restart=False,
update=False,
user=None,
conf_file=None,
bin_env=None,
**kwargs):
'''
Ensure the named service is running.
name
Service name as defined in the supervisor configuration file
restart
Whether to force a restart
update
Whether to update the supervisor configuration.
user
Name of the user to run the supervisorctl command
.. versionadded:: 0.17.0
conf_file
path to supervisorctl config file
bin_env
path to supervisorctl bin or path to virtualenv with supervisor
installed
'''
if name.endswith(':*'):
name = name[:-1]
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if 'supervisord.status' not in __salt__:
ret['result'] = False
ret['comment'] = 'Supervisord module not activated. Do you need to install supervisord?'
return ret
all_processes = __salt__['supervisord.status'](
user=user,
conf_file=conf_file,
bin_env=bin_env
)
# parse process groups
process_groups = set()
for proc in all_processes:
if ':' in proc:
process_groups.add(proc[:proc.index(':') + 1])
process_groups = sorted(process_groups)
matches = {}
if name in all_processes:
matches[name] = (all_processes[name]['state'].lower() == 'running')
elif name in process_groups:
for process in (x for x in all_processes if x.startswith(name)):
matches[process] = (
all_processes[process]['state'].lower() == 'running'
)
to_add = not bool(matches)
if __opts__['test']:
if not to_add:
# Process/group already present, check if any need to be started
to_start = [x for x, y in six.iteritems(matches) if y is False]
if to_start:
ret['result'] = None
if name.endswith(':'):
# Process group
if len(to_start) == len(matches):
ret['comment'] = (
'All services in group \'{0}\' will be started'
.format(name)
)
else:
ret['comment'] = (
'The following services will be started: {0}'
.format(' '.join(to_start))
)
else:
# Single program
ret['comment'] = 'Service {0} will be started'.format(name)
else:
if name.endswith(':'):
# Process group
ret['comment'] = (
'All services in group \'{0}\' are already running'
.format(name)
)
else:
ret['comment'] = ('Service {0} is already running'
.format(name))
else:
ret['result'] = None
# Process/group needs to be added
if name.endswith(':'):
_type = 'Group \'{0}\''.format(name)
else:
_type = 'Service {0}'.format(name)
ret['comment'] = '{0} will be added and started'.format(_type)
return ret
changes = []
just_updated = False
if update:
# If the state explicitly asks to update, we don't care if the process
# is being added or not, since it'll take care of this for us,
# so give this condition priority in order
#
# That is, unless `to_add` somehow manages to contain processes
# we don't want running, in which case adding them may be a mistake
comment = 'Updating supervisor'
result = __salt__['supervisord.update'](
user=user,
conf_file=conf_file,
bin_env=bin_env
)
ret.update(_check_error(result, comment))
log.debug(comment)
if '{0}: updated'.format(name) in result:
just_updated = True
elif to_add:
# Not sure if this condition is precise enough.
comment = 'Adding service: {0}'.format(name)
__salt__['supervisord.reread'](
user=user,
conf_file=conf_file,
bin_env=bin_env
)
# Causes supervisorctl to throw `ERROR: process group already active`
# if process group exists. At this moment, I'm not sure how to handle
# this outside of grepping out the expected string in `_check_error`.
result = __salt__['supervisord.add'](
name,
user=user,
conf_file=conf_file,
bin_env=bin_env
)
ret.update(_check_error(result, comment))
changes.append(comment)
log.debug(comment)
is_stopped = None
process_type = None
if name in process_groups:
process_type = 'group'
# check if any processes in this group are stopped
is_stopped = False
for proc in all_processes:
if proc.startswith(name) \
and _is_stopped_state(all_processes[proc]['state']):
is_stopped = True
break
elif name in all_processes:
process_type = 'service'
if _is_stopped_state(all_processes[name]['state']):
is_stopped = True
else:
is_stopped = False
if is_stopped is False:
if restart and not just_updated:
comment = 'Restarting{0}: {1}'.format(
process_type is not None and ' {0}'.format(process_type) or '',
name
)
log.debug(comment)
result = __salt__['supervisord.restart'](
name,
user=user,
conf_file=conf_file,
bin_env=bin_env
)
ret.update(_check_error(result, comment))
changes.append(comment)
elif just_updated:
comment = 'Not starting updated{0}: {1}'.format(
process_type is not None and ' {0}'.format(process_type) or '',
name
)
result = comment
ret.update({'comment': comment})
else:
comment = 'Not starting already running{0}: {1}'.format(
process_type is not None and ' {0}'.format(process_type) or '',
name
)
result = comment
ret.update({'comment': comment})
elif not just_updated:
comment = 'Starting{0}: {1}'.format(
process_type is not None and ' {0}'.format(process_type) or '',
name
)
changes.append(comment)
log.debug(comment)
result = __salt__['supervisord.start'](
name,
user=user,
conf_file=conf_file,
bin_env=bin_env
)
ret.update(_check_error(result, comment))
log.debug(six.text_type(result))
if ret['result'] and changes:
ret['changes'][name] = ' '.join(changes)
return ret | python | def running(name,
restart=False,
update=False,
user=None,
conf_file=None,
bin_env=None,
**kwargs):
'''
Ensure the named service is running.
name
Service name as defined in the supervisor configuration file
restart
Whether to force a restart
update
Whether to update the supervisor configuration.
user
Name of the user to run the supervisorctl command
.. versionadded:: 0.17.0
conf_file
path to supervisorctl config file
bin_env
path to supervisorctl bin or path to virtualenv with supervisor
installed
'''
if name.endswith(':*'):
name = name[:-1]
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if 'supervisord.status' not in __salt__:
ret['result'] = False
ret['comment'] = 'Supervisord module not activated. Do you need to install supervisord?'
return ret
all_processes = __salt__['supervisord.status'](
user=user,
conf_file=conf_file,
bin_env=bin_env
)
# parse process groups
process_groups = set()
for proc in all_processes:
if ':' in proc:
process_groups.add(proc[:proc.index(':') + 1])
process_groups = sorted(process_groups)
matches = {}
if name in all_processes:
matches[name] = (all_processes[name]['state'].lower() == 'running')
elif name in process_groups:
for process in (x for x in all_processes if x.startswith(name)):
matches[process] = (
all_processes[process]['state'].lower() == 'running'
)
to_add = not bool(matches)
if __opts__['test']:
if not to_add:
# Process/group already present, check if any need to be started
to_start = [x for x, y in six.iteritems(matches) if y is False]
if to_start:
ret['result'] = None
if name.endswith(':'):
# Process group
if len(to_start) == len(matches):
ret['comment'] = (
'All services in group \'{0}\' will be started'
.format(name)
)
else:
ret['comment'] = (
'The following services will be started: {0}'
.format(' '.join(to_start))
)
else:
# Single program
ret['comment'] = 'Service {0} will be started'.format(name)
else:
if name.endswith(':'):
# Process group
ret['comment'] = (
'All services in group \'{0}\' are already running'
.format(name)
)
else:
ret['comment'] = ('Service {0} is already running'
.format(name))
else:
ret['result'] = None
# Process/group needs to be added
if name.endswith(':'):
_type = 'Group \'{0}\''.format(name)
else:
_type = 'Service {0}'.format(name)
ret['comment'] = '{0} will be added and started'.format(_type)
return ret
changes = []
just_updated = False
if update:
# If the state explicitly asks to update, we don't care if the process
# is being added or not, since it'll take care of this for us,
# so give this condition priority in order
#
# That is, unless `to_add` somehow manages to contain processes
# we don't want running, in which case adding them may be a mistake
comment = 'Updating supervisor'
result = __salt__['supervisord.update'](
user=user,
conf_file=conf_file,
bin_env=bin_env
)
ret.update(_check_error(result, comment))
log.debug(comment)
if '{0}: updated'.format(name) in result:
just_updated = True
elif to_add:
# Not sure if this condition is precise enough.
comment = 'Adding service: {0}'.format(name)
__salt__['supervisord.reread'](
user=user,
conf_file=conf_file,
bin_env=bin_env
)
# Causes supervisorctl to throw `ERROR: process group already active`
# if process group exists. At this moment, I'm not sure how to handle
# this outside of grepping out the expected string in `_check_error`.
result = __salt__['supervisord.add'](
name,
user=user,
conf_file=conf_file,
bin_env=bin_env
)
ret.update(_check_error(result, comment))
changes.append(comment)
log.debug(comment)
is_stopped = None
process_type = None
if name in process_groups:
process_type = 'group'
# check if any processes in this group are stopped
is_stopped = False
for proc in all_processes:
if proc.startswith(name) \
and _is_stopped_state(all_processes[proc]['state']):
is_stopped = True
break
elif name in all_processes:
process_type = 'service'
if _is_stopped_state(all_processes[name]['state']):
is_stopped = True
else:
is_stopped = False
if is_stopped is False:
if restart and not just_updated:
comment = 'Restarting{0}: {1}'.format(
process_type is not None and ' {0}'.format(process_type) or '',
name
)
log.debug(comment)
result = __salt__['supervisord.restart'](
name,
user=user,
conf_file=conf_file,
bin_env=bin_env
)
ret.update(_check_error(result, comment))
changes.append(comment)
elif just_updated:
comment = 'Not starting updated{0}: {1}'.format(
process_type is not None and ' {0}'.format(process_type) or '',
name
)
result = comment
ret.update({'comment': comment})
else:
comment = 'Not starting already running{0}: {1}'.format(
process_type is not None and ' {0}'.format(process_type) or '',
name
)
result = comment
ret.update({'comment': comment})
elif not just_updated:
comment = 'Starting{0}: {1}'.format(
process_type is not None and ' {0}'.format(process_type) or '',
name
)
changes.append(comment)
log.debug(comment)
result = __salt__['supervisord.start'](
name,
user=user,
conf_file=conf_file,
bin_env=bin_env
)
ret.update(_check_error(result, comment))
log.debug(six.text_type(result))
if ret['result'] and changes:
ret['changes'][name] = ' '.join(changes)
return ret | [
"def",
"running",
"(",
"name",
",",
"restart",
"=",
"False",
",",
"update",
"=",
"False",
",",
"user",
"=",
"None",
",",
"conf_file",
"=",
"None",
",",
"bin_env",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"name",
".",
"endswith",
"(",
... | Ensure the named service is running.
name
Service name as defined in the supervisor configuration file
restart
Whether to force a restart
update
Whether to update the supervisor configuration.
user
Name of the user to run the supervisorctl command
.. versionadded:: 0.17.0
conf_file
path to supervisorctl config file
bin_env
path to supervisorctl bin or path to virtualenv with supervisor
installed | [
"Ensure",
"the",
"named",
"service",
"is",
"running",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/supervisord.py#L52-L272 | train |
saltstack/salt | salt/states/supervisord.py | dead | def dead(name,
user=None,
conf_file=None,
bin_env=None,
**kwargs):
'''
Ensure the named service is dead (not running).
name
Service name as defined in the supervisor configuration file
user
Name of the user to run the supervisorctl command
.. versionadded:: 0.17.0
conf_file
path to supervisorctl config file
bin_env
path to supervisorctl bin or path to virtualenv with supervisor
installed
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if __opts__['test']:
ret['result'] = None
ret['comment'] = (
'Service {0} is set to be stopped'.format(name))
else:
comment = 'Stopping service: {0}'.format(name)
log.debug(comment)
all_processes = __salt__['supervisord.status'](
user=user,
conf_file=conf_file,
bin_env=bin_env
)
# parse process groups
process_groups = []
for proc in all_processes:
if ':' in proc:
process_groups.append(proc[:proc.index(':') + 1])
process_groups = list(set(process_groups))
is_stopped = None
if name in process_groups:
# check if any processes in this group are stopped
is_stopped = False
for proc in all_processes:
if proc.startswith(name) \
and _is_stopped_state(all_processes[proc]['state']):
is_stopped = True
break
elif name in all_processes:
if _is_stopped_state(all_processes[name]['state']):
is_stopped = True
else:
is_stopped = False
else:
# process name doesn't exist
ret['comment'] = "Service {0} doesn't exist".format(name)
return ret
if is_stopped is True:
ret['comment'] = "Service {0} is not running".format(name)
else:
result = {name: __salt__['supervisord.stop'](
name,
user=user,
conf_file=conf_file,
bin_env=bin_env
)}
ret.update(_check_error(result, comment))
ret['changes'][name] = comment
log.debug(six.text_type(result))
return ret | python | def dead(name,
user=None,
conf_file=None,
bin_env=None,
**kwargs):
'''
Ensure the named service is dead (not running).
name
Service name as defined in the supervisor configuration file
user
Name of the user to run the supervisorctl command
.. versionadded:: 0.17.0
conf_file
path to supervisorctl config file
bin_env
path to supervisorctl bin or path to virtualenv with supervisor
installed
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
if __opts__['test']:
ret['result'] = None
ret['comment'] = (
'Service {0} is set to be stopped'.format(name))
else:
comment = 'Stopping service: {0}'.format(name)
log.debug(comment)
all_processes = __salt__['supervisord.status'](
user=user,
conf_file=conf_file,
bin_env=bin_env
)
# parse process groups
process_groups = []
for proc in all_processes:
if ':' in proc:
process_groups.append(proc[:proc.index(':') + 1])
process_groups = list(set(process_groups))
is_stopped = None
if name in process_groups:
# check if any processes in this group are stopped
is_stopped = False
for proc in all_processes:
if proc.startswith(name) \
and _is_stopped_state(all_processes[proc]['state']):
is_stopped = True
break
elif name in all_processes:
if _is_stopped_state(all_processes[name]['state']):
is_stopped = True
else:
is_stopped = False
else:
# process name doesn't exist
ret['comment'] = "Service {0} doesn't exist".format(name)
return ret
if is_stopped is True:
ret['comment'] = "Service {0} is not running".format(name)
else:
result = {name: __salt__['supervisord.stop'](
name,
user=user,
conf_file=conf_file,
bin_env=bin_env
)}
ret.update(_check_error(result, comment))
ret['changes'][name] = comment
log.debug(six.text_type(result))
return ret | [
"def",
"dead",
"(",
"name",
",",
"user",
"=",
"None",
",",
"conf_file",
"=",
"None",
",",
"bin_env",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''"... | Ensure the named service is dead (not running).
name
Service name as defined in the supervisor configuration file
user
Name of the user to run the supervisorctl command
.. versionadded:: 0.17.0
conf_file
path to supervisorctl config file
bin_env
path to supervisorctl bin or path to virtualenv with supervisor
installed | [
"Ensure",
"the",
"named",
"service",
"is",
"dead",
"(",
"not",
"running",
")",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/supervisord.py#L275-L355 | train |
saltstack/salt | salt/states/supervisord.py | mod_watch | def mod_watch(name,
restart=True,
update=False,
user=None,
conf_file=None,
bin_env=None,
**kwargs):
'''
The supervisord watcher, called to invoke the watch command.
Always restart on watch
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the state being triggered.
'''
return running(
name,
restart=restart,
update=update,
user=user,
conf_file=conf_file,
bin_env=bin_env
) | python | def mod_watch(name,
restart=True,
update=False,
user=None,
conf_file=None,
bin_env=None,
**kwargs):
'''
The supervisord watcher, called to invoke the watch command.
Always restart on watch
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the state being triggered.
'''
return running(
name,
restart=restart,
update=update,
user=user,
conf_file=conf_file,
bin_env=bin_env
) | [
"def",
"mod_watch",
"(",
"name",
",",
"restart",
"=",
"True",
",",
"update",
"=",
"False",
",",
"user",
"=",
"None",
",",
"conf_file",
"=",
"None",
",",
"bin_env",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"running",
"(",
"name",
",... | The supervisord watcher, called to invoke the watch command.
Always restart on watch
.. note::
This state exists to support special handling of the ``watch``
:ref:`requisite <requisites>`. It should not be called directly.
Parameters for this function should be set by the state being triggered. | [
"The",
"supervisord",
"watcher",
"called",
"to",
"invoke",
"the",
"watch",
"command",
".",
"Always",
"restart",
"on",
"watch"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/supervisord.py#L358-L382 | train |
saltstack/salt | salt/renderers/cheetah.py | render | def render(cheetah_data, saltenv='base', sls='', method='xml', **kws):
'''
Render a Cheetah template.
:rtype: A Python data structure
'''
if not HAS_LIBS:
return {}
if not isinstance(cheetah_data, six.string_types):
cheetah_data = cheetah_data.read()
if cheetah_data.startswith('#!'):
cheetah_data = cheetah_data[(cheetah_data.find('\n') + 1):]
if not cheetah_data.strip():
return {}
return six.text_type(Template(cheetah_data, searchList=[kws])) | python | def render(cheetah_data, saltenv='base', sls='', method='xml', **kws):
'''
Render a Cheetah template.
:rtype: A Python data structure
'''
if not HAS_LIBS:
return {}
if not isinstance(cheetah_data, six.string_types):
cheetah_data = cheetah_data.read()
if cheetah_data.startswith('#!'):
cheetah_data = cheetah_data[(cheetah_data.find('\n') + 1):]
if not cheetah_data.strip():
return {}
return six.text_type(Template(cheetah_data, searchList=[kws])) | [
"def",
"render",
"(",
"cheetah_data",
",",
"saltenv",
"=",
"'base'",
",",
"sls",
"=",
"''",
",",
"method",
"=",
"'xml'",
",",
"*",
"*",
"kws",
")",
":",
"if",
"not",
"HAS_LIBS",
":",
"return",
"{",
"}",
"if",
"not",
"isinstance",
"(",
"cheetah_data",... | Render a Cheetah template.
:rtype: A Python data structure | [
"Render",
"a",
"Cheetah",
"template",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/cheetah.py#L19-L36 | train |
saltstack/salt | salt/modules/nagios_rpc.py | _config | def _config():
'''
Get configuration items for URL, Username and Password
'''
status_url = __salt__['config.get']('nagios.status_url') or \
__salt__['config.get']('nagios:status_url')
if not status_url:
raise CommandExecutionError('Missing Nagios URL in the configuration.')
username = __salt__['config.get']('nagios.username') or \
__salt__['config.get']('nagios:username')
password = __salt__['config.get']('nagios.password') or \
__salt__['config.get']('nagios:password')
return {
'url': status_url,
'username': username,
'password': password
} | python | def _config():
'''
Get configuration items for URL, Username and Password
'''
status_url = __salt__['config.get']('nagios.status_url') or \
__salt__['config.get']('nagios:status_url')
if not status_url:
raise CommandExecutionError('Missing Nagios URL in the configuration.')
username = __salt__['config.get']('nagios.username') or \
__salt__['config.get']('nagios:username')
password = __salt__['config.get']('nagios.password') or \
__salt__['config.get']('nagios:password')
return {
'url': status_url,
'username': username,
'password': password
} | [
"def",
"_config",
"(",
")",
":",
"status_url",
"=",
"__salt__",
"[",
"'config.get'",
"]",
"(",
"'nagios.status_url'",
")",
"or",
"__salt__",
"[",
"'config.get'",
"]",
"(",
"'nagios:status_url'",
")",
"if",
"not",
"status_url",
":",
"raise",
"CommandExecutionErro... | Get configuration items for URL, Username and Password | [
"Get",
"configuration",
"items",
"for",
"URL",
"Username",
"and",
"Password"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nagios_rpc.py#L32-L49 | train |
saltstack/salt | salt/modules/nagios_rpc.py | _status_query | def _status_query(query, hostname, enumerate=None, service=None):
'''
Send query along to Nagios.
'''
config = _config()
data = None
params = {
'hostname': hostname,
'query': query,
}
ret = {
'result': False
}
if enumerate:
params['formatoptions'] = 'enumerate'
if service:
params['servicedescription'] = service
if config['username'] and config['password'] is not None:
auth = (config['username'], config['password'],)
else:
auth = None
try:
result = salt.utils.http.query(
config['url'],
method='GET',
params=params,
decode=True,
data=data,
text=True,
status=True,
header_dict={},
auth=auth,
backend='requests',
opts=__opts__,
)
except ValueError:
ret['error'] = 'Please ensure Nagios is running.'
ret['result'] = False
return ret
if result.get('status', None) == salt.ext.six.moves.http_client.OK:
try:
ret['json_data'] = result['dict']
ret['result'] = True
except ValueError:
ret['error'] = 'Please ensure Nagios is running.'
elif result.get('status', None) == salt.ext.six.moves.http_client.UNAUTHORIZED:
ret['error'] = 'Authentication failed. Please check the configuration.'
elif result.get('status', None) == salt.ext.six.moves.http_client.NOT_FOUND:
ret['error'] = 'URL {0} was not found.'.format(config['url'])
else:
ret['error'] = 'Results: {0}'.format(result.text)
return ret | python | def _status_query(query, hostname, enumerate=None, service=None):
'''
Send query along to Nagios.
'''
config = _config()
data = None
params = {
'hostname': hostname,
'query': query,
}
ret = {
'result': False
}
if enumerate:
params['formatoptions'] = 'enumerate'
if service:
params['servicedescription'] = service
if config['username'] and config['password'] is not None:
auth = (config['username'], config['password'],)
else:
auth = None
try:
result = salt.utils.http.query(
config['url'],
method='GET',
params=params,
decode=True,
data=data,
text=True,
status=True,
header_dict={},
auth=auth,
backend='requests',
opts=__opts__,
)
except ValueError:
ret['error'] = 'Please ensure Nagios is running.'
ret['result'] = False
return ret
if result.get('status', None) == salt.ext.six.moves.http_client.OK:
try:
ret['json_data'] = result['dict']
ret['result'] = True
except ValueError:
ret['error'] = 'Please ensure Nagios is running.'
elif result.get('status', None) == salt.ext.six.moves.http_client.UNAUTHORIZED:
ret['error'] = 'Authentication failed. Please check the configuration.'
elif result.get('status', None) == salt.ext.six.moves.http_client.NOT_FOUND:
ret['error'] = 'URL {0} was not found.'.format(config['url'])
else:
ret['error'] = 'Results: {0}'.format(result.text)
return ret | [
"def",
"_status_query",
"(",
"query",
",",
"hostname",
",",
"enumerate",
"=",
"None",
",",
"service",
"=",
"None",
")",
":",
"config",
"=",
"_config",
"(",
")",
"data",
"=",
"None",
"params",
"=",
"{",
"'hostname'",
":",
"hostname",
",",
"'query'",
":"... | Send query along to Nagios. | [
"Send",
"query",
"along",
"to",
"Nagios",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nagios_rpc.py#L52-L110 | train |
saltstack/salt | salt/modules/nagios_rpc.py | host_status | def host_status(hostname=None, **kwargs):
'''
Check status of a particular host By default
statuses are returned in a numeric format.
Parameters:
hostname
The hostname to check the status of the service in Nagios.
numeric
Turn to false in order to return status in text format
('OK' instead of 0, 'Warning' instead of 1 etc)
:return: status: 'OK', 'Warning', 'Critical' or 'Unknown'
CLI Example:
.. code-block:: bash
salt '*' nagios_rpc.host_status hostname=webserver.domain.com
salt '*' nagios_rpc.host_status hostname=webserver.domain.com numeric=False
'''
if not hostname:
raise CommandExecutionError('Missing hostname parameter')
target = 'host'
numeric = kwargs.get('numeric')
data = _status_query(target, hostname, enumerate=numeric)
ret = {'result': data['result']}
if ret['result']:
ret['status'] = data.get('json_data', {}).get('data', {}).get(target, {}).get('status',
not numeric and 'Unknown' or 2)
else:
ret['error'] = data['error']
return ret | python | def host_status(hostname=None, **kwargs):
'''
Check status of a particular host By default
statuses are returned in a numeric format.
Parameters:
hostname
The hostname to check the status of the service in Nagios.
numeric
Turn to false in order to return status in text format
('OK' instead of 0, 'Warning' instead of 1 etc)
:return: status: 'OK', 'Warning', 'Critical' or 'Unknown'
CLI Example:
.. code-block:: bash
salt '*' nagios_rpc.host_status hostname=webserver.domain.com
salt '*' nagios_rpc.host_status hostname=webserver.domain.com numeric=False
'''
if not hostname:
raise CommandExecutionError('Missing hostname parameter')
target = 'host'
numeric = kwargs.get('numeric')
data = _status_query(target, hostname, enumerate=numeric)
ret = {'result': data['result']}
if ret['result']:
ret['status'] = data.get('json_data', {}).get('data', {}).get(target, {}).get('status',
not numeric and 'Unknown' or 2)
else:
ret['error'] = data['error']
return ret | [
"def",
"host_status",
"(",
"hostname",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"hostname",
":",
"raise",
"CommandExecutionError",
"(",
"'Missing hostname parameter'",
")",
"target",
"=",
"'host'",
"numeric",
"=",
"kwargs",
".",
"get",
"(... | Check status of a particular host By default
statuses are returned in a numeric format.
Parameters:
hostname
The hostname to check the status of the service in Nagios.
numeric
Turn to false in order to return status in text format
('OK' instead of 0, 'Warning' instead of 1 etc)
:return: status: 'OK', 'Warning', 'Critical' or 'Unknown'
CLI Example:
.. code-block:: bash
salt '*' nagios_rpc.host_status hostname=webserver.domain.com
salt '*' nagios_rpc.host_status hostname=webserver.domain.com numeric=False | [
"Check",
"status",
"of",
"a",
"particular",
"host",
"By",
"default",
"statuses",
"are",
"returned",
"in",
"a",
"numeric",
"format",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nagios_rpc.py#L113-L150 | train |
saltstack/salt | salt/modules/nagios_rpc.py | service_status | def service_status(hostname=None, service=None, **kwargs):
'''
Check status of a particular service on a host on it in Nagios.
By default statuses are returned in a numeric format.
Parameters:
hostname
The hostname to check the status of the service in Nagios.
service
The service to check the status of in Nagios.
numeric
Turn to false in order to return status in text format
('OK' instead of 0, 'Warning' instead of 1 etc)
:return: status: 'OK', 'Warning', 'Critical' or 'Unknown'
CLI Example:
.. code-block:: bash
salt '*' nagios_rpc.service_status hostname=webserver.domain.com service='HTTP'
salt '*' nagios_rpc.service_status hostname=webserver.domain.com service='HTTP' numeric=False
'''
if not hostname:
raise CommandExecutionError('Missing hostname parameter')
if not service:
raise CommandExecutionError('Missing service parameter')
target = 'service'
numeric = kwargs.get('numeric')
data = _status_query(target, hostname, service=service, enumerate=numeric)
ret = {'result': data['result']}
if ret['result']:
ret['status'] = data.get('json_data', {}).get('data', {}).get(target, {}).get('status',
not numeric and 'Unknown' or 2)
else:
ret['error'] = data['error']
return ret | python | def service_status(hostname=None, service=None, **kwargs):
'''
Check status of a particular service on a host on it in Nagios.
By default statuses are returned in a numeric format.
Parameters:
hostname
The hostname to check the status of the service in Nagios.
service
The service to check the status of in Nagios.
numeric
Turn to false in order to return status in text format
('OK' instead of 0, 'Warning' instead of 1 etc)
:return: status: 'OK', 'Warning', 'Critical' or 'Unknown'
CLI Example:
.. code-block:: bash
salt '*' nagios_rpc.service_status hostname=webserver.domain.com service='HTTP'
salt '*' nagios_rpc.service_status hostname=webserver.domain.com service='HTTP' numeric=False
'''
if not hostname:
raise CommandExecutionError('Missing hostname parameter')
if not service:
raise CommandExecutionError('Missing service parameter')
target = 'service'
numeric = kwargs.get('numeric')
data = _status_query(target, hostname, service=service, enumerate=numeric)
ret = {'result': data['result']}
if ret['result']:
ret['status'] = data.get('json_data', {}).get('data', {}).get(target, {}).get('status',
not numeric and 'Unknown' or 2)
else:
ret['error'] = data['error']
return ret | [
"def",
"service_status",
"(",
"hostname",
"=",
"None",
",",
"service",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"hostname",
":",
"raise",
"CommandExecutionError",
"(",
"'Missing hostname parameter'",
")",
"if",
"not",
"service",
":",
"rai... | Check status of a particular service on a host on it in Nagios.
By default statuses are returned in a numeric format.
Parameters:
hostname
The hostname to check the status of the service in Nagios.
service
The service to check the status of in Nagios.
numeric
Turn to false in order to return status in text format
('OK' instead of 0, 'Warning' instead of 1 etc)
:return: status: 'OK', 'Warning', 'Critical' or 'Unknown'
CLI Example:
.. code-block:: bash
salt '*' nagios_rpc.service_status hostname=webserver.domain.com service='HTTP'
salt '*' nagios_rpc.service_status hostname=webserver.domain.com service='HTTP' numeric=False | [
"Check",
"status",
"of",
"a",
"particular",
"service",
"on",
"a",
"host",
"on",
"it",
"in",
"Nagios",
".",
"By",
"default",
"statuses",
"are",
"returned",
"in",
"a",
"numeric",
"format",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/nagios_rpc.py#L153-L196 | train |
saltstack/salt | salt/sdb/keyring_db.py | set_ | def set_(key, value, service=None, profile=None):
'''
Set a key/value pair in a keyring service
'''
service = _get_service(service, profile)
keyring.set_password(service, key, value) | python | def set_(key, value, service=None, profile=None):
'''
Set a key/value pair in a keyring service
'''
service = _get_service(service, profile)
keyring.set_password(service, key, value) | [
"def",
"set_",
"(",
"key",
",",
"value",
",",
"service",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"service",
"=",
"_get_service",
"(",
"service",
",",
"profile",
")",
"keyring",
".",
"set_password",
"(",
"service",
",",
"key",
",",
"value",
... | Set a key/value pair in a keyring service | [
"Set",
"a",
"key",
"/",
"value",
"pair",
"in",
"a",
"keyring",
"service"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/keyring_db.py#L76-L81 | train |
saltstack/salt | salt/sdb/keyring_db.py | get | def get(key, service=None, profile=None):
'''
Get a value from a keyring service
'''
service = _get_service(service, profile)
return keyring.get_password(service, key) | python | def get(key, service=None, profile=None):
'''
Get a value from a keyring service
'''
service = _get_service(service, profile)
return keyring.get_password(service, key) | [
"def",
"get",
"(",
"key",
",",
"service",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"service",
"=",
"_get_service",
"(",
"service",
",",
"profile",
")",
"return",
"keyring",
".",
"get_password",
"(",
"service",
",",
"key",
")"
] | Get a value from a keyring service | [
"Get",
"a",
"value",
"from",
"a",
"keyring",
"service"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/sdb/keyring_db.py#L84-L89 | train |
saltstack/salt | salt/returners/sentry_return.py | returner | def returner(ret):
'''
Log outcome to sentry. The returner tries to identify errors and report
them as such. All other messages will be reported at info level.
Failed states will be appended as separate list for convenience.
'''
try:
_connect_sentry(_get_message(ret), ret)
except Exception as err:
log.error('Can\'t run connect_sentry: %s', err, exc_info=True) | python | def returner(ret):
'''
Log outcome to sentry. The returner tries to identify errors and report
them as such. All other messages will be reported at info level.
Failed states will be appended as separate list for convenience.
'''
try:
_connect_sentry(_get_message(ret), ret)
except Exception as err:
log.error('Can\'t run connect_sentry: %s', err, exc_info=True) | [
"def",
"returner",
"(",
"ret",
")",
":",
"try",
":",
"_connect_sentry",
"(",
"_get_message",
"(",
"ret",
")",
",",
"ret",
")",
"except",
"Exception",
"as",
"err",
":",
"log",
".",
"error",
"(",
"'Can\\'t run connect_sentry: %s'",
",",
"err",
",",
"exc_info... | Log outcome to sentry. The returner tries to identify errors and report
them as such. All other messages will be reported at info level.
Failed states will be appended as separate list for convenience. | [
"Log",
"outcome",
"to",
"sentry",
".",
"The",
"returner",
"tries",
"to",
"identify",
"errors",
"and",
"report",
"them",
"as",
"such",
".",
"All",
"other",
"messages",
"will",
"be",
"reported",
"at",
"info",
"level",
".",
"Failed",
"states",
"will",
"be",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/sentry_return.py#L74-L84 | train |
saltstack/salt | salt/returners/sentry_return.py | _connect_sentry | def _connect_sentry(message, result):
'''
Connect to the Sentry server
'''
pillar_data = __salt__['pillar.raw']()
grains = __salt__['grains.items']()
raven_config = pillar_data['raven']
hide_pillar = raven_config.get('hide_pillar')
sentry_data = {
'result': result,
'pillar': 'HIDDEN' if hide_pillar else pillar_data,
'grains': grains
}
data = {
'platform': 'python',
'culprit': message,
'level': 'error'
}
tags = {}
if 'tags' in raven_config:
for tag in raven_config['tags']:
tags[tag] = grains[tag]
if _ret_is_not_error(result):
data['level'] = 'info'
if raven_config.get('report_errors_only') and data['level'] != 'error':
return
if raven_config.get('dsn'):
client = Client(raven_config.get('dsn'), transport=HTTPTransport)
else:
try:
servers = []
for server in raven_config['servers']:
servers.append(server + '/api/store/')
client = Client(
servers=servers,
public_key=raven_config['public_key'],
secret_key=raven_config['secret_key'],
project=raven_config['project'],
transport=HTTPTransport
)
except KeyError as missing_key:
log.error(
'Sentry returner needs key \'%s\' in pillar',
missing_key
)
return
try:
msgid = client.capture(
'raven.events.Message',
message=message,
data=data,
extra=sentry_data,
tags=tags
)
log.info('Message id %s written to sentry', msgid)
except Exception as exc:
log.error('Can\'t send message to sentry: %s', exc, exc_info=True) | python | def _connect_sentry(message, result):
'''
Connect to the Sentry server
'''
pillar_data = __salt__['pillar.raw']()
grains = __salt__['grains.items']()
raven_config = pillar_data['raven']
hide_pillar = raven_config.get('hide_pillar')
sentry_data = {
'result': result,
'pillar': 'HIDDEN' if hide_pillar else pillar_data,
'grains': grains
}
data = {
'platform': 'python',
'culprit': message,
'level': 'error'
}
tags = {}
if 'tags' in raven_config:
for tag in raven_config['tags']:
tags[tag] = grains[tag]
if _ret_is_not_error(result):
data['level'] = 'info'
if raven_config.get('report_errors_only') and data['level'] != 'error':
return
if raven_config.get('dsn'):
client = Client(raven_config.get('dsn'), transport=HTTPTransport)
else:
try:
servers = []
for server in raven_config['servers']:
servers.append(server + '/api/store/')
client = Client(
servers=servers,
public_key=raven_config['public_key'],
secret_key=raven_config['secret_key'],
project=raven_config['project'],
transport=HTTPTransport
)
except KeyError as missing_key:
log.error(
'Sentry returner needs key \'%s\' in pillar',
missing_key
)
return
try:
msgid = client.capture(
'raven.events.Message',
message=message,
data=data,
extra=sentry_data,
tags=tags
)
log.info('Message id %s written to sentry', msgid)
except Exception as exc:
log.error('Can\'t send message to sentry: %s', exc, exc_info=True) | [
"def",
"_connect_sentry",
"(",
"message",
",",
"result",
")",
":",
"pillar_data",
"=",
"__salt__",
"[",
"'pillar.raw'",
"]",
"(",
")",
"grains",
"=",
"__salt__",
"[",
"'grains.items'",
"]",
"(",
")",
"raven_config",
"=",
"pillar_data",
"[",
"'raven'",
"]",
... | Connect to the Sentry server | [
"Connect",
"to",
"the",
"Sentry",
"server"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/sentry_return.py#L120-L180 | train |
saltstack/salt | salt/modules/vboxmanage.py | list_nodes_min | def list_nodes_min():
'''
Return a list of registered VMs, with minimal information
CLI Example:
.. code-block:: bash
salt '*' vboxmanage.list_nodes_min
'''
ret = {}
cmd = '{0} list vms'.format(vboxcmd())
for line in salt.modules.cmdmod.run(cmd).splitlines():
if not line.strip():
continue
comps = line.split()
name = comps[0].replace('"', '')
ret[name] = True
return ret | python | def list_nodes_min():
'''
Return a list of registered VMs, with minimal information
CLI Example:
.. code-block:: bash
salt '*' vboxmanage.list_nodes_min
'''
ret = {}
cmd = '{0} list vms'.format(vboxcmd())
for line in salt.modules.cmdmod.run(cmd).splitlines():
if not line.strip():
continue
comps = line.split()
name = comps[0].replace('"', '')
ret[name] = True
return ret | [
"def",
"list_nodes_min",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"cmd",
"=",
"'{0} list vms'",
".",
"format",
"(",
"vboxcmd",
"(",
")",
")",
"for",
"line",
"in",
"salt",
".",
"modules",
".",
"cmdmod",
".",
"run",
"(",
"cmd",
")",
".",
"splitlines",
"(... | Return a list of registered VMs, with minimal information
CLI Example:
.. code-block:: bash
salt '*' vboxmanage.list_nodes_min | [
"Return",
"a",
"list",
"of",
"registered",
"VMs",
"with",
"minimal",
"information"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vboxmanage.py#L77-L95 | train |
saltstack/salt | salt/modules/vboxmanage.py | list_nodes | def list_nodes():
'''
Return a list of registered VMs
CLI Example:
.. code-block:: bash
salt '*' vboxmanage.list_nodes
'''
ret = {}
nodes = list_nodes_full()
for node in nodes:
ret[node] = {
'id': nodes[node]['UUID'],
'image': nodes[node]['Guest OS'],
'name': nodes[node]['Name'],
'state': None,
'private_ips': [],
'public_ips': [],
}
ret[node]['size'] = '{0} RAM, {1} CPU'.format(
nodes[node]['Memory size'],
nodes[node]['Number of CPUs'],
)
return ret | python | def list_nodes():
'''
Return a list of registered VMs
CLI Example:
.. code-block:: bash
salt '*' vboxmanage.list_nodes
'''
ret = {}
nodes = list_nodes_full()
for node in nodes:
ret[node] = {
'id': nodes[node]['UUID'],
'image': nodes[node]['Guest OS'],
'name': nodes[node]['Name'],
'state': None,
'private_ips': [],
'public_ips': [],
}
ret[node]['size'] = '{0} RAM, {1} CPU'.format(
nodes[node]['Memory size'],
nodes[node]['Number of CPUs'],
)
return ret | [
"def",
"list_nodes",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"nodes",
"=",
"list_nodes_full",
"(",
")",
"for",
"node",
"in",
"nodes",
":",
"ret",
"[",
"node",
"]",
"=",
"{",
"'id'",
":",
"nodes",
"[",
"node",
"]",
"[",
"'UUID'",
"]",
",",
"'image'",... | Return a list of registered VMs
CLI Example:
.. code-block:: bash
salt '*' vboxmanage.list_nodes | [
"Return",
"a",
"list",
"of",
"registered",
"VMs"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vboxmanage.py#L111-L136 | train |
saltstack/salt | salt/modules/vboxmanage.py | start | def start(name):
'''
Start a VM
CLI Example:
.. code-block:: bash
salt '*' vboxmanage.start my_vm
'''
ret = {}
cmd = '{0} startvm {1}'.format(vboxcmd(), name)
ret = salt.modules.cmdmod.run(cmd).splitlines()
return ret | python | def start(name):
'''
Start a VM
CLI Example:
.. code-block:: bash
salt '*' vboxmanage.start my_vm
'''
ret = {}
cmd = '{0} startvm {1}'.format(vboxcmd(), name)
ret = salt.modules.cmdmod.run(cmd).splitlines()
return ret | [
"def",
"start",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"}",
"cmd",
"=",
"'{0} startvm {1}'",
".",
"format",
"(",
"vboxcmd",
"(",
")",
",",
"name",
")",
"ret",
"=",
"salt",
".",
"modules",
".",
"cmdmod",
".",
"run",
"(",
"cmd",
")",
".",
"splitli... | Start a VM
CLI Example:
.. code-block:: bash
salt '*' vboxmanage.start my_vm | [
"Start",
"a",
"VM"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vboxmanage.py#L139-L152 | train |
saltstack/salt | salt/modules/vboxmanage.py | register | def register(filename):
'''
Register a VM
CLI Example:
.. code-block:: bash
salt '*' vboxmanage.register my_vm_filename
'''
if not os.path.isfile(filename):
raise CommandExecutionError(
'The specified filename ({0}) does not exist.'.format(filename)
)
cmd = '{0} registervm {1}'.format(vboxcmd(), filename)
ret = salt.modules.cmdmod.run_all(cmd)
if ret['retcode'] == 0:
return True
return ret['stderr'] | python | def register(filename):
'''
Register a VM
CLI Example:
.. code-block:: bash
salt '*' vboxmanage.register my_vm_filename
'''
if not os.path.isfile(filename):
raise CommandExecutionError(
'The specified filename ({0}) does not exist.'.format(filename)
)
cmd = '{0} registervm {1}'.format(vboxcmd(), filename)
ret = salt.modules.cmdmod.run_all(cmd)
if ret['retcode'] == 0:
return True
return ret['stderr'] | [
"def",
"register",
"(",
"filename",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'The specified filename ({0}) does not exist.'",
".",
"format",
"(",
"filename",
")",
")",
"cmd",
"=... | Register a VM
CLI Example:
.. code-block:: bash
salt '*' vboxmanage.register my_vm_filename | [
"Register",
"a",
"VM"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vboxmanage.py#L170-L189 | train |
saltstack/salt | salt/modules/vboxmanage.py | unregister | def unregister(name, delete=False):
'''
Unregister a VM
CLI Example:
.. code-block:: bash
salt '*' vboxmanage.unregister my_vm_filename
'''
nodes = list_nodes_min()
if name not in nodes:
raise CommandExecutionError(
'The specified VM ({0}) is not registered.'.format(name)
)
cmd = '{0} unregistervm {1}'.format(vboxcmd(), name)
if delete is True:
cmd += ' --delete'
ret = salt.modules.cmdmod.run_all(cmd)
if ret['retcode'] == 0:
return True
return ret['stderr'] | python | def unregister(name, delete=False):
'''
Unregister a VM
CLI Example:
.. code-block:: bash
salt '*' vboxmanage.unregister my_vm_filename
'''
nodes = list_nodes_min()
if name not in nodes:
raise CommandExecutionError(
'The specified VM ({0}) is not registered.'.format(name)
)
cmd = '{0} unregistervm {1}'.format(vboxcmd(), name)
if delete is True:
cmd += ' --delete'
ret = salt.modules.cmdmod.run_all(cmd)
if ret['retcode'] == 0:
return True
return ret['stderr'] | [
"def",
"unregister",
"(",
"name",
",",
"delete",
"=",
"False",
")",
":",
"nodes",
"=",
"list_nodes_min",
"(",
")",
"if",
"name",
"not",
"in",
"nodes",
":",
"raise",
"CommandExecutionError",
"(",
"'The specified VM ({0}) is not registered.'",
".",
"format",
"(",
... | Unregister a VM
CLI Example:
.. code-block:: bash
salt '*' vboxmanage.unregister my_vm_filename | [
"Unregister",
"a",
"VM"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vboxmanage.py#L192-L214 | train |
saltstack/salt | salt/modules/vboxmanage.py | create | def create(name,
groups=None,
ostype=None,
register=True,
basefolder=None,
new_uuid=None,
**kwargs):
'''
Create a new VM
CLI Example:
.. code-block:: bash
salt 'hypervisor' vboxmanage.create <name>
'''
nodes = list_nodes_min()
if name in nodes:
raise CommandExecutionError(
'The specified VM ({0}) is already registered.'.format(name)
)
params = ''
if name:
if NAME_RE.search(name):
raise CommandExecutionError('New VM name contains invalid characters')
params += ' --name {0}'.format(name)
if groups:
if isinstance(groups, six.string_types):
groups = [groups]
if isinstance(groups, list):
params += ' --groups {0}'.format(','.join(groups))
else:
raise CommandExecutionError(
'groups must be either a string or a list of strings'
)
ostypes = list_ostypes()
if ostype not in ostypes:
raise CommandExecutionError(
'The specified OS type ({0}) is not available.'.format(name)
)
else:
params += ' --ostype ' + ostype
if register is True:
params += ' --register'
if basefolder:
if not os.path.exists(basefolder):
raise CommandExecutionError('basefolder {0} was not found'.format(basefolder))
params += ' --basefolder {0}'.format(basefolder)
if new_uuid:
if NAME_RE.search(new_uuid):
raise CommandExecutionError('New UUID contains invalid characters')
params += ' --uuid {0}'.format(new_uuid)
cmd = '{0} create {1}'.format(vboxcmd(), params)
ret = salt.modules.cmdmod.run_all(cmd)
if ret['retcode'] == 0:
return True
return ret['stderr'] | python | def create(name,
groups=None,
ostype=None,
register=True,
basefolder=None,
new_uuid=None,
**kwargs):
'''
Create a new VM
CLI Example:
.. code-block:: bash
salt 'hypervisor' vboxmanage.create <name>
'''
nodes = list_nodes_min()
if name in nodes:
raise CommandExecutionError(
'The specified VM ({0}) is already registered.'.format(name)
)
params = ''
if name:
if NAME_RE.search(name):
raise CommandExecutionError('New VM name contains invalid characters')
params += ' --name {0}'.format(name)
if groups:
if isinstance(groups, six.string_types):
groups = [groups]
if isinstance(groups, list):
params += ' --groups {0}'.format(','.join(groups))
else:
raise CommandExecutionError(
'groups must be either a string or a list of strings'
)
ostypes = list_ostypes()
if ostype not in ostypes:
raise CommandExecutionError(
'The specified OS type ({0}) is not available.'.format(name)
)
else:
params += ' --ostype ' + ostype
if register is True:
params += ' --register'
if basefolder:
if not os.path.exists(basefolder):
raise CommandExecutionError('basefolder {0} was not found'.format(basefolder))
params += ' --basefolder {0}'.format(basefolder)
if new_uuid:
if NAME_RE.search(new_uuid):
raise CommandExecutionError('New UUID contains invalid characters')
params += ' --uuid {0}'.format(new_uuid)
cmd = '{0} create {1}'.format(vboxcmd(), params)
ret = salt.modules.cmdmod.run_all(cmd)
if ret['retcode'] == 0:
return True
return ret['stderr'] | [
"def",
"create",
"(",
"name",
",",
"groups",
"=",
"None",
",",
"ostype",
"=",
"None",
",",
"register",
"=",
"True",
",",
"basefolder",
"=",
"None",
",",
"new_uuid",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"nodes",
"=",
"list_nodes_min",
"(",
... | Create a new VM
CLI Example:
.. code-block:: bash
salt 'hypervisor' vboxmanage.create <name> | [
"Create",
"a",
"new",
"VM"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vboxmanage.py#L230-L294 | train |
saltstack/salt | salt/modules/vboxmanage.py | clonevm | def clonevm(name=None,
uuid=None,
new_name=None,
snapshot_uuid=None,
snapshot_name=None,
mode='machine',
options=None,
basefolder=None,
new_uuid=None,
register=False,
groups=None,
**kwargs):
'''
Clone a new VM from an existing VM
CLI Example:
.. code-block:: bash
salt 'hypervisor' vboxmanage.clonevm <name> <new_name>
'''
if (name and uuid) or (not name and not uuid):
raise CommandExecutionError(
'Either a name or a uuid must be specified, but not both.'
)
params = ''
nodes_names = list_nodes_min()
nodes_uuids = list_items('vms', True, 'UUID').keys()
if name:
if name not in nodes_names:
raise CommandExecutionError(
'The specified VM ({0}) is not registered.'.format(name)
)
params += ' ' + name
elif uuid:
if uuid not in nodes_uuids:
raise CommandExecutionError(
'The specified VM ({0}) is not registered.'.format(name)
)
params += ' ' + uuid
if snapshot_name and snapshot_uuid:
raise CommandExecutionError(
'Either a snapshot_name or a snapshot_uuid may be specified, but not both'
)
if snapshot_name:
if NAME_RE.search(snapshot_name):
raise CommandExecutionError('Snapshot name contains invalid characters')
params += ' --snapshot {0}'.format(snapshot_name)
elif snapshot_uuid:
if UUID_RE.search(snapshot_uuid):
raise CommandExecutionError('Snapshot name contains invalid characters')
params += ' --snapshot {0}'.format(snapshot_uuid)
valid_modes = ('machine', 'machineandchildren', 'all')
if mode and mode not in valid_modes:
raise CommandExecutionError(
'Mode must be one of: {0} (default "machine")'.format(', '.join(valid_modes))
)
else:
params += ' --mode ' + mode
valid_options = ('link', 'keepallmacs', 'keepnatmacs', 'keepdisknames')
if options and options not in valid_options:
raise CommandExecutionError(
'If specified, options must be one of: {0}'.format(', '.join(valid_options))
)
else:
params += ' --options ' + options
if new_name:
if NAME_RE.search(new_name):
raise CommandExecutionError('New name contains invalid characters')
params += ' --name {0}'.format(new_name)
if groups:
if isinstance(groups, six.string_types):
groups = [groups]
if isinstance(groups, list):
params += ' --groups {0}'.format(','.join(groups))
else:
raise CommandExecutionError(
'groups must be either a string or a list of strings'
)
if basefolder:
if not os.path.exists(basefolder):
raise CommandExecutionError('basefolder {0} was not found'.format(basefolder))
params += ' --basefolder {0}'.format(basefolder)
if new_uuid:
if NAME_RE.search(new_uuid):
raise CommandExecutionError('New UUID contains invalid characters')
params += ' --uuid {0}'.format(new_uuid)
if register is True:
params += ' --register'
cmd = '{0} clonevm {1}'.format(vboxcmd(), name)
ret = salt.modules.cmdmod.run_all(cmd)
if ret['retcode'] == 0:
return True
return ret['stderr'] | python | def clonevm(name=None,
uuid=None,
new_name=None,
snapshot_uuid=None,
snapshot_name=None,
mode='machine',
options=None,
basefolder=None,
new_uuid=None,
register=False,
groups=None,
**kwargs):
'''
Clone a new VM from an existing VM
CLI Example:
.. code-block:: bash
salt 'hypervisor' vboxmanage.clonevm <name> <new_name>
'''
if (name and uuid) or (not name and not uuid):
raise CommandExecutionError(
'Either a name or a uuid must be specified, but not both.'
)
params = ''
nodes_names = list_nodes_min()
nodes_uuids = list_items('vms', True, 'UUID').keys()
if name:
if name not in nodes_names:
raise CommandExecutionError(
'The specified VM ({0}) is not registered.'.format(name)
)
params += ' ' + name
elif uuid:
if uuid not in nodes_uuids:
raise CommandExecutionError(
'The specified VM ({0}) is not registered.'.format(name)
)
params += ' ' + uuid
if snapshot_name and snapshot_uuid:
raise CommandExecutionError(
'Either a snapshot_name or a snapshot_uuid may be specified, but not both'
)
if snapshot_name:
if NAME_RE.search(snapshot_name):
raise CommandExecutionError('Snapshot name contains invalid characters')
params += ' --snapshot {0}'.format(snapshot_name)
elif snapshot_uuid:
if UUID_RE.search(snapshot_uuid):
raise CommandExecutionError('Snapshot name contains invalid characters')
params += ' --snapshot {0}'.format(snapshot_uuid)
valid_modes = ('machine', 'machineandchildren', 'all')
if mode and mode not in valid_modes:
raise CommandExecutionError(
'Mode must be one of: {0} (default "machine")'.format(', '.join(valid_modes))
)
else:
params += ' --mode ' + mode
valid_options = ('link', 'keepallmacs', 'keepnatmacs', 'keepdisknames')
if options and options not in valid_options:
raise CommandExecutionError(
'If specified, options must be one of: {0}'.format(', '.join(valid_options))
)
else:
params += ' --options ' + options
if new_name:
if NAME_RE.search(new_name):
raise CommandExecutionError('New name contains invalid characters')
params += ' --name {0}'.format(new_name)
if groups:
if isinstance(groups, six.string_types):
groups = [groups]
if isinstance(groups, list):
params += ' --groups {0}'.format(','.join(groups))
else:
raise CommandExecutionError(
'groups must be either a string or a list of strings'
)
if basefolder:
if not os.path.exists(basefolder):
raise CommandExecutionError('basefolder {0} was not found'.format(basefolder))
params += ' --basefolder {0}'.format(basefolder)
if new_uuid:
if NAME_RE.search(new_uuid):
raise CommandExecutionError('New UUID contains invalid characters')
params += ' --uuid {0}'.format(new_uuid)
if register is True:
params += ' --register'
cmd = '{0} clonevm {1}'.format(vboxcmd(), name)
ret = salt.modules.cmdmod.run_all(cmd)
if ret['retcode'] == 0:
return True
return ret['stderr'] | [
"def",
"clonevm",
"(",
"name",
"=",
"None",
",",
"uuid",
"=",
"None",
",",
"new_name",
"=",
"None",
",",
"snapshot_uuid",
"=",
"None",
",",
"snapshot_name",
"=",
"None",
",",
"mode",
"=",
"'machine'",
",",
"options",
"=",
"None",
",",
"basefolder",
"="... | Clone a new VM from an existing VM
CLI Example:
.. code-block:: bash
salt 'hypervisor' vboxmanage.clonevm <name> <new_name> | [
"Clone",
"a",
"new",
"VM",
"from",
"an",
"existing",
"VM"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vboxmanage.py#L297-L401 | train |
saltstack/salt | salt/modules/vboxmanage.py | clonemedium | def clonemedium(medium,
uuid_in=None,
file_in=None,
uuid_out=None,
file_out=None,
mformat=None,
variant=None,
existing=False,
**kwargs):
'''
Clone a new VM from an existing VM
CLI Example:
.. code-block:: bash
salt 'hypervisor' vboxmanage.clonemedium <name> <new_name>
'''
params = ''
valid_mediums = ('disk', 'dvd', 'floppy')
if medium in valid_mediums:
params += medium
else:
raise CommandExecutionError(
'Medium must be one of: {0}.'.format(', '.join(valid_mediums))
)
if (uuid_in and file_in) or (not uuid_in and not file_in):
raise CommandExecutionError(
'Either uuid_in or file_in must be used, but not both.'
)
if uuid_in:
if medium == 'disk':
item = 'hdds'
elif medium == 'dvd':
item = 'dvds'
elif medium == 'floppy':
item = 'floppies'
items = list_items(item)
if uuid_in not in items:
raise CommandExecutionError('UUID {0} was not found'.format(uuid_in))
params += ' ' + uuid_in
elif file_in:
if not os.path.exists(file_in):
raise CommandExecutionError('File {0} was not found'.format(file_in))
params += ' ' + file_in
if (uuid_out and file_out) or (not uuid_out and not file_out):
raise CommandExecutionError(
'Either uuid_out or file_out must be used, but not both.'
)
if uuid_out:
params += ' ' + uuid_out
elif file_out:
try:
salt.utils.files.fopen(file_out, 'w').close() # pylint: disable=resource-leakage
os.unlink(file_out)
params += ' ' + file_out
except OSError:
raise CommandExecutionError('{0} is not a valid filename'.format(file_out))
if mformat:
valid_mformat = ('VDI', 'VMDK', 'VHD', 'RAW')
if mformat not in valid_mformat:
raise CommandExecutionError(
'If specified, mformat must be one of: {0}'.format(', '.join(valid_mformat))
)
else:
params += ' --format ' + mformat
valid_variant = ('Standard', 'Fixed', 'Split2G', 'Stream', 'ESX')
if variant and variant not in valid_variant:
if not os.path.exists(file_in):
raise CommandExecutionError(
'If specified, variant must be one of: {0}'.format(', '.join(valid_variant))
)
else:
params += ' --variant ' + variant
if existing:
params += ' --existing'
cmd = '{0} clonemedium {1}'.format(vboxcmd(), params)
ret = salt.modules.cmdmod.run_all(cmd)
if ret['retcode'] == 0:
return True
return ret['stderr'] | python | def clonemedium(medium,
uuid_in=None,
file_in=None,
uuid_out=None,
file_out=None,
mformat=None,
variant=None,
existing=False,
**kwargs):
'''
Clone a new VM from an existing VM
CLI Example:
.. code-block:: bash
salt 'hypervisor' vboxmanage.clonemedium <name> <new_name>
'''
params = ''
valid_mediums = ('disk', 'dvd', 'floppy')
if medium in valid_mediums:
params += medium
else:
raise CommandExecutionError(
'Medium must be one of: {0}.'.format(', '.join(valid_mediums))
)
if (uuid_in and file_in) or (not uuid_in and not file_in):
raise CommandExecutionError(
'Either uuid_in or file_in must be used, but not both.'
)
if uuid_in:
if medium == 'disk':
item = 'hdds'
elif medium == 'dvd':
item = 'dvds'
elif medium == 'floppy':
item = 'floppies'
items = list_items(item)
if uuid_in not in items:
raise CommandExecutionError('UUID {0} was not found'.format(uuid_in))
params += ' ' + uuid_in
elif file_in:
if not os.path.exists(file_in):
raise CommandExecutionError('File {0} was not found'.format(file_in))
params += ' ' + file_in
if (uuid_out and file_out) or (not uuid_out and not file_out):
raise CommandExecutionError(
'Either uuid_out or file_out must be used, but not both.'
)
if uuid_out:
params += ' ' + uuid_out
elif file_out:
try:
salt.utils.files.fopen(file_out, 'w').close() # pylint: disable=resource-leakage
os.unlink(file_out)
params += ' ' + file_out
except OSError:
raise CommandExecutionError('{0} is not a valid filename'.format(file_out))
if mformat:
valid_mformat = ('VDI', 'VMDK', 'VHD', 'RAW')
if mformat not in valid_mformat:
raise CommandExecutionError(
'If specified, mformat must be one of: {0}'.format(', '.join(valid_mformat))
)
else:
params += ' --format ' + mformat
valid_variant = ('Standard', 'Fixed', 'Split2G', 'Stream', 'ESX')
if variant and variant not in valid_variant:
if not os.path.exists(file_in):
raise CommandExecutionError(
'If specified, variant must be one of: {0}'.format(', '.join(valid_variant))
)
else:
params += ' --variant ' + variant
if existing:
params += ' --existing'
cmd = '{0} clonemedium {1}'.format(vboxcmd(), params)
ret = salt.modules.cmdmod.run_all(cmd)
if ret['retcode'] == 0:
return True
return ret['stderr'] | [
"def",
"clonemedium",
"(",
"medium",
",",
"uuid_in",
"=",
"None",
",",
"file_in",
"=",
"None",
",",
"uuid_out",
"=",
"None",
",",
"file_out",
"=",
"None",
",",
"mformat",
"=",
"None",
",",
"variant",
"=",
"None",
",",
"existing",
"=",
"False",
",",
"... | Clone a new VM from an existing VM
CLI Example:
.. code-block:: bash
salt 'hypervisor' vboxmanage.clonemedium <name> <new_name> | [
"Clone",
"a",
"new",
"VM",
"from",
"an",
"existing",
"VM"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vboxmanage.py#L404-L494 | train |
saltstack/salt | salt/modules/vboxmanage.py | list_items | def list_items(item, details=False, group_by='UUID'):
'''
Return a list of a specific type of item. The following items are available:
vms
runningvms
ostypes
hostdvds
hostfloppies
intnets
bridgedifs
hostonlyifs
natnets
dhcpservers
hostinfo
hostcpuids
hddbackends
hdds
dvds
floppies
usbhost
usbfilters
systemproperties
extpacks
groups
webcams
screenshotformats
CLI Example:
.. code-block:: bash
salt 'hypervisor' vboxmanage.items <item>
salt 'hypervisor' vboxmanage.items <item> details=True
salt 'hypervisor' vboxmanage.items <item> details=True group_by=Name
Some items do not display well, or at all, unless ``details`` is set to
``True``. By default, items are grouped by the ``UUID`` field, but not all
items contain that field. In those cases, another field must be specified.
'''
types = (
'vms', 'runningvms', 'ostypes', 'hostdvds', 'hostfloppies', 'intnets',
'bridgedifs', 'hostonlyifs', 'natnets', 'dhcpservers', 'hostinfo',
'hostcpuids', 'hddbackends', 'hdds', 'dvds', 'floppies', 'usbhost',
'usbfilters', 'systemproperties', 'extpacks', 'groups', 'webcams',
'screenshotformats'
)
if item not in types:
raise CommandExecutionError(
'Item must be one of: {0}.'.format(', '.join(types))
)
flag = ''
if details is True:
flag = ' -l'
ret = {}
tmp_id = None
tmp_dict = {}
cmd = '{0} list{1} {2}'.format(vboxcmd(), flag, item)
for line in salt.modules.cmdmod.run(cmd).splitlines():
if not line.strip():
continue
comps = line.split(':')
if not comps:
continue
if tmp_id is not None:
ret[tmp_id] = tmp_dict
line_val = ':'.join(comps[1:]).strip()
if comps[0] == group_by:
tmp_id = line_val
tmp_dict = {}
tmp_dict[comps[0]] = line_val
return ret | python | def list_items(item, details=False, group_by='UUID'):
'''
Return a list of a specific type of item. The following items are available:
vms
runningvms
ostypes
hostdvds
hostfloppies
intnets
bridgedifs
hostonlyifs
natnets
dhcpservers
hostinfo
hostcpuids
hddbackends
hdds
dvds
floppies
usbhost
usbfilters
systemproperties
extpacks
groups
webcams
screenshotformats
CLI Example:
.. code-block:: bash
salt 'hypervisor' vboxmanage.items <item>
salt 'hypervisor' vboxmanage.items <item> details=True
salt 'hypervisor' vboxmanage.items <item> details=True group_by=Name
Some items do not display well, or at all, unless ``details`` is set to
``True``. By default, items are grouped by the ``UUID`` field, but not all
items contain that field. In those cases, another field must be specified.
'''
types = (
'vms', 'runningvms', 'ostypes', 'hostdvds', 'hostfloppies', 'intnets',
'bridgedifs', 'hostonlyifs', 'natnets', 'dhcpservers', 'hostinfo',
'hostcpuids', 'hddbackends', 'hdds', 'dvds', 'floppies', 'usbhost',
'usbfilters', 'systemproperties', 'extpacks', 'groups', 'webcams',
'screenshotformats'
)
if item not in types:
raise CommandExecutionError(
'Item must be one of: {0}.'.format(', '.join(types))
)
flag = ''
if details is True:
flag = ' -l'
ret = {}
tmp_id = None
tmp_dict = {}
cmd = '{0} list{1} {2}'.format(vboxcmd(), flag, item)
for line in salt.modules.cmdmod.run(cmd).splitlines():
if not line.strip():
continue
comps = line.split(':')
if not comps:
continue
if tmp_id is not None:
ret[tmp_id] = tmp_dict
line_val = ':'.join(comps[1:]).strip()
if comps[0] == group_by:
tmp_id = line_val
tmp_dict = {}
tmp_dict[comps[0]] = line_val
return ret | [
"def",
"list_items",
"(",
"item",
",",
"details",
"=",
"False",
",",
"group_by",
"=",
"'UUID'",
")",
":",
"types",
"=",
"(",
"'vms'",
",",
"'runningvms'",
",",
"'ostypes'",
",",
"'hostdvds'",
",",
"'hostfloppies'",
",",
"'intnets'",
",",
"'bridgedifs'",
",... | Return a list of a specific type of item. The following items are available:
vms
runningvms
ostypes
hostdvds
hostfloppies
intnets
bridgedifs
hostonlyifs
natnets
dhcpservers
hostinfo
hostcpuids
hddbackends
hdds
dvds
floppies
usbhost
usbfilters
systemproperties
extpacks
groups
webcams
screenshotformats
CLI Example:
.. code-block:: bash
salt 'hypervisor' vboxmanage.items <item>
salt 'hypervisor' vboxmanage.items <item> details=True
salt 'hypervisor' vboxmanage.items <item> details=True group_by=Name
Some items do not display well, or at all, unless ``details`` is set to
``True``. By default, items are grouped by the ``UUID`` field, but not all
items contain that field. In those cases, another field must be specified. | [
"Return",
"a",
"list",
"of",
"a",
"specific",
"type",
"of",
"item",
".",
"The",
"following",
"items",
"are",
"available",
":"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/vboxmanage.py#L497-L571 | train |
saltstack/salt | salt/modules/oracle.py | _unicode_output | def _unicode_output(cursor, name, default_type, size, precision, scale):
'''
Return strings values as python unicode string
http://www.oracle.com/technetwork/articles/dsl/tuininga-cx-oracle-084866.html
'''
if default_type in (cx_Oracle.STRING, cx_Oracle.LONG_STRING,
cx_Oracle.FIXED_CHAR, cx_Oracle.CLOB):
return cursor.var(six.text_type, size, cursor.arraysize) | python | def _unicode_output(cursor, name, default_type, size, precision, scale):
'''
Return strings values as python unicode string
http://www.oracle.com/technetwork/articles/dsl/tuininga-cx-oracle-084866.html
'''
if default_type in (cx_Oracle.STRING, cx_Oracle.LONG_STRING,
cx_Oracle.FIXED_CHAR, cx_Oracle.CLOB):
return cursor.var(six.text_type, size, cursor.arraysize) | [
"def",
"_unicode_output",
"(",
"cursor",
",",
"name",
",",
"default_type",
",",
"size",
",",
"precision",
",",
"scale",
")",
":",
"if",
"default_type",
"in",
"(",
"cx_Oracle",
".",
"STRING",
",",
"cx_Oracle",
".",
"LONG_STRING",
",",
"cx_Oracle",
".",
"FIX... | Return strings values as python unicode string
http://www.oracle.com/technetwork/articles/dsl/tuininga-cx-oracle-084866.html | [
"Return",
"strings",
"values",
"as",
"python",
"unicode",
"string"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/oracle.py#L80-L88 | train |
saltstack/salt | salt/modules/oracle.py | _connect | def _connect(uri):
'''
uri = user/password@host[:port]/sid[servicename as {sysdba|sysoper}]
or
uri = sid[ as {sysdba|sysoper}]
(this syntax only makes sense on non-Windows minions, ORAHOME is taken from oratab)
Return cx_Oracle.Connection instance
'''
# cx_Oracle.Connection() does not support 'as sysdba' syntax
uri_l = uri.rsplit(' as ', 1)
if len(uri_l) == 2:
credentials, mode = uri_l
mode = MODE[mode]
else:
credentials = uri_l[0]
mode = 0
# force UTF-8 client encoding
os.environ['NLS_LANG'] = '.AL32UTF8'
if '@' in uri:
serv_name = False
userpass, hostportsid = credentials.split('@')
user, password = userpass.split('/')
hostport, sid = hostportsid.split('/')
if 'servicename' in sid:
serv_name = True
sid = sid.split('servicename')[0].strip()
hostport_l = hostport.split(':')
if len(hostport_l) == 2:
host, port = hostport_l
else:
host = hostport_l[0]
port = 1521
log.debug('connect: %s', (user, password, host, port, sid, mode))
if serv_name:
conn = cx_Oracle.connect(user, password, cx_Oracle.makedsn(host, port, service_name=sid), mode)
else:
conn = cx_Oracle.connect(user, password, cx_Oracle.makedsn(host, port, sid), mode)
else:
sid = uri.rsplit(' as ', 1)[0]
orahome = _parse_oratab(sid)
if orahome:
os.environ['ORACLE_HOME'] = orahome
else:
raise CommandExecutionError('No uri defined and SID {0} not found in oratab'.format(sid))
os.environ['ORACLE_SID'] = sid
log.debug('connect: %s', (sid, mode))
conn = cx_Oracle.connect(mode=MODE['sysdba'])
conn.outputtypehandler = _unicode_output
return conn | python | def _connect(uri):
'''
uri = user/password@host[:port]/sid[servicename as {sysdba|sysoper}]
or
uri = sid[ as {sysdba|sysoper}]
(this syntax only makes sense on non-Windows minions, ORAHOME is taken from oratab)
Return cx_Oracle.Connection instance
'''
# cx_Oracle.Connection() does not support 'as sysdba' syntax
uri_l = uri.rsplit(' as ', 1)
if len(uri_l) == 2:
credentials, mode = uri_l
mode = MODE[mode]
else:
credentials = uri_l[0]
mode = 0
# force UTF-8 client encoding
os.environ['NLS_LANG'] = '.AL32UTF8'
if '@' in uri:
serv_name = False
userpass, hostportsid = credentials.split('@')
user, password = userpass.split('/')
hostport, sid = hostportsid.split('/')
if 'servicename' in sid:
serv_name = True
sid = sid.split('servicename')[0].strip()
hostport_l = hostport.split(':')
if len(hostport_l) == 2:
host, port = hostport_l
else:
host = hostport_l[0]
port = 1521
log.debug('connect: %s', (user, password, host, port, sid, mode))
if serv_name:
conn = cx_Oracle.connect(user, password, cx_Oracle.makedsn(host, port, service_name=sid), mode)
else:
conn = cx_Oracle.connect(user, password, cx_Oracle.makedsn(host, port, sid), mode)
else:
sid = uri.rsplit(' as ', 1)[0]
orahome = _parse_oratab(sid)
if orahome:
os.environ['ORACLE_HOME'] = orahome
else:
raise CommandExecutionError('No uri defined and SID {0} not found in oratab'.format(sid))
os.environ['ORACLE_SID'] = sid
log.debug('connect: %s', (sid, mode))
conn = cx_Oracle.connect(mode=MODE['sysdba'])
conn.outputtypehandler = _unicode_output
return conn | [
"def",
"_connect",
"(",
"uri",
")",
":",
"# cx_Oracle.Connection() does not support 'as sysdba' syntax",
"uri_l",
"=",
"uri",
".",
"rsplit",
"(",
"' as '",
",",
"1",
")",
"if",
"len",
"(",
"uri_l",
")",
"==",
"2",
":",
"credentials",
",",
"mode",
"=",
"uri_l... | uri = user/password@host[:port]/sid[servicename as {sysdba|sysoper}]
or
uri = sid[ as {sysdba|sysoper}]
(this syntax only makes sense on non-Windows minions, ORAHOME is taken from oratab)
Return cx_Oracle.Connection instance | [
"uri",
"=",
"user",
"/",
"password@host",
"[",
":",
"port",
"]",
"/",
"sid",
"[",
"servicename",
"as",
"{",
"sysdba|sysoper",
"}",
"]",
"or",
"uri",
"=",
"sid",
"[",
"as",
"{",
"sysdba|sysoper",
"}",
"]",
"(",
"this",
"syntax",
"only",
"makes",
"sens... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/oracle.py#L91-L140 | train |
saltstack/salt | salt/modules/oracle.py | _parse_oratab | def _parse_oratab(sid):
'''
Return ORACLE_HOME for a given SID found in oratab
Note: only works with Unix-like minions
'''
if __grains__.get('kernel') in ('Linux', 'AIX', 'FreeBSD', 'OpenBSD', 'NetBSD'):
ORATAB = '/etc/oratab'
elif __grains__.get('kernel') in 'SunOS':
ORATAB = '/var/opt/oracle/oratab'
else:
# Windows has no oratab file
raise CommandExecutionError(
'No uri defined for {0} and oratab not available in this OS'.format(sid))
with fopen(ORATAB, 'r') as f:
while True:
line = f.readline()
if not line:
break
if line.startswith('#'):
continue
if sid in line.split(':')[0]:
return line.split(':')[1]
return None | python | def _parse_oratab(sid):
'''
Return ORACLE_HOME for a given SID found in oratab
Note: only works with Unix-like minions
'''
if __grains__.get('kernel') in ('Linux', 'AIX', 'FreeBSD', 'OpenBSD', 'NetBSD'):
ORATAB = '/etc/oratab'
elif __grains__.get('kernel') in 'SunOS':
ORATAB = '/var/opt/oracle/oratab'
else:
# Windows has no oratab file
raise CommandExecutionError(
'No uri defined for {0} and oratab not available in this OS'.format(sid))
with fopen(ORATAB, 'r') as f:
while True:
line = f.readline()
if not line:
break
if line.startswith('#'):
continue
if sid in line.split(':')[0]:
return line.split(':')[1]
return None | [
"def",
"_parse_oratab",
"(",
"sid",
")",
":",
"if",
"__grains__",
".",
"get",
"(",
"'kernel'",
")",
"in",
"(",
"'Linux'",
",",
"'AIX'",
",",
"'FreeBSD'",
",",
"'OpenBSD'",
",",
"'NetBSD'",
")",
":",
"ORATAB",
"=",
"'/etc/oratab'",
"elif",
"__grains__",
"... | Return ORACLE_HOME for a given SID found in oratab
Note: only works with Unix-like minions | [
"Return",
"ORACLE_HOME",
"for",
"a",
"given",
"SID",
"found",
"in",
"oratab"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/oracle.py#L143-L166 | train |
saltstack/salt | salt/modules/oracle.py | run_query | def run_query(db, query):
'''
Run SQL query and return result
CLI Example:
.. code-block:: bash
salt '*' oracle.run_query my_db "select * from my_table"
'''
if db in [x.keys()[0] for x in show_dbs()]:
conn = _connect(show_dbs(db)[db]['uri'])
else:
log.debug('No uri found in pillars - will try to use oratab')
# if db does not have uri defined in pillars
# or it's not defined in pillars at all parse oratab file
conn = _connect(uri=db)
return conn.cursor().execute(query).fetchall() | python | def run_query(db, query):
'''
Run SQL query and return result
CLI Example:
.. code-block:: bash
salt '*' oracle.run_query my_db "select * from my_table"
'''
if db in [x.keys()[0] for x in show_dbs()]:
conn = _connect(show_dbs(db)[db]['uri'])
else:
log.debug('No uri found in pillars - will try to use oratab')
# if db does not have uri defined in pillars
# or it's not defined in pillars at all parse oratab file
conn = _connect(uri=db)
return conn.cursor().execute(query).fetchall() | [
"def",
"run_query",
"(",
"db",
",",
"query",
")",
":",
"if",
"db",
"in",
"[",
"x",
".",
"keys",
"(",
")",
"[",
"0",
"]",
"for",
"x",
"in",
"show_dbs",
"(",
")",
"]",
":",
"conn",
"=",
"_connect",
"(",
"show_dbs",
"(",
"db",
")",
"[",
"db",
... | Run SQL query and return result
CLI Example:
.. code-block:: bash
salt '*' oracle.run_query my_db "select * from my_table" | [
"Run",
"SQL",
"query",
"and",
"return",
"result"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/oracle.py#L170-L187 | train |
saltstack/salt | salt/modules/oracle.py | show_dbs | def show_dbs(*dbs):
'''
Show databases configuration from pillar. Filter by `*args`
CLI Example:
.. code-block:: bash
salt '*' oracle.show_dbs
salt '*' oracle.show_dbs my_db
'''
if dbs:
log.debug('get db versions for: %s', dbs)
result = {}
for db in dbs:
result[db] = __salt__['pillar.get']('oracle:dbs:' + db)
return result
else:
pillar_dbs = __salt__['pillar.get']('oracle:dbs')
log.debug('get all (%s) dbs versions', len(pillar_dbs))
return pillar_dbs | python | def show_dbs(*dbs):
'''
Show databases configuration from pillar. Filter by `*args`
CLI Example:
.. code-block:: bash
salt '*' oracle.show_dbs
salt '*' oracle.show_dbs my_db
'''
if dbs:
log.debug('get db versions for: %s', dbs)
result = {}
for db in dbs:
result[db] = __salt__['pillar.get']('oracle:dbs:' + db)
return result
else:
pillar_dbs = __salt__['pillar.get']('oracle:dbs')
log.debug('get all (%s) dbs versions', len(pillar_dbs))
return pillar_dbs | [
"def",
"show_dbs",
"(",
"*",
"dbs",
")",
":",
"if",
"dbs",
":",
"log",
".",
"debug",
"(",
"'get db versions for: %s'",
",",
"dbs",
")",
"result",
"=",
"{",
"}",
"for",
"db",
"in",
"dbs",
":",
"result",
"[",
"db",
"]",
"=",
"__salt__",
"[",
"'pillar... | Show databases configuration from pillar. Filter by `*args`
CLI Example:
.. code-block:: bash
salt '*' oracle.show_dbs
salt '*' oracle.show_dbs my_db | [
"Show",
"databases",
"configuration",
"from",
"pillar",
".",
"Filter",
"by",
"*",
"args"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/oracle.py#L190-L210 | train |
saltstack/salt | salt/modules/oracle.py | version | def version(*dbs):
'''
Server Version (select banner from v$version)
CLI Example:
.. code-block:: bash
salt '*' oracle.version
salt '*' oracle.version my_db
'''
pillar_dbs = __salt__['pillar.get']('oracle:dbs')
get_version = lambda x: [
r[0] for r in run_query(x, "select banner from v$version order by banner")
]
result = {}
if dbs:
log.debug('get db versions for: %s', dbs)
for db in dbs:
if db in pillar_dbs:
result[db] = get_version(db)
else:
log.debug('get all(%s) dbs versions', len(dbs))
for db in dbs:
result[db] = get_version(db)
return result | python | def version(*dbs):
'''
Server Version (select banner from v$version)
CLI Example:
.. code-block:: bash
salt '*' oracle.version
salt '*' oracle.version my_db
'''
pillar_dbs = __salt__['pillar.get']('oracle:dbs')
get_version = lambda x: [
r[0] for r in run_query(x, "select banner from v$version order by banner")
]
result = {}
if dbs:
log.debug('get db versions for: %s', dbs)
for db in dbs:
if db in pillar_dbs:
result[db] = get_version(db)
else:
log.debug('get all(%s) dbs versions', len(dbs))
for db in dbs:
result[db] = get_version(db)
return result | [
"def",
"version",
"(",
"*",
"dbs",
")",
":",
"pillar_dbs",
"=",
"__salt__",
"[",
"'pillar.get'",
"]",
"(",
"'oracle:dbs'",
")",
"get_version",
"=",
"lambda",
"x",
":",
"[",
"r",
"[",
"0",
"]",
"for",
"r",
"in",
"run_query",
"(",
"x",
",",
"\"select b... | Server Version (select banner from v$version)
CLI Example:
.. code-block:: bash
salt '*' oracle.version
salt '*' oracle.version my_db | [
"Server",
"Version",
"(",
"select",
"banner",
"from",
"v$version",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/oracle.py#L214-L239 | train |
saltstack/salt | salt/modules/oracle.py | show_env | def show_env():
'''
Show Environment used by Oracle Client
CLI Example:
.. code-block:: bash
salt '*' oracle.show_env
.. note::
at first _connect() ``NLS_LANG`` will forced to '.AL32UTF8'
'''
envs = ['PATH', 'ORACLE_HOME', 'TNS_ADMIN', 'NLS_LANG']
result = {}
for env in envs:
if env in os.environ:
result[env] = os.environ[env]
return result | python | def show_env():
'''
Show Environment used by Oracle Client
CLI Example:
.. code-block:: bash
salt '*' oracle.show_env
.. note::
at first _connect() ``NLS_LANG`` will forced to '.AL32UTF8'
'''
envs = ['PATH', 'ORACLE_HOME', 'TNS_ADMIN', 'NLS_LANG']
result = {}
for env in envs:
if env in os.environ:
result[env] = os.environ[env]
return result | [
"def",
"show_env",
"(",
")",
":",
"envs",
"=",
"[",
"'PATH'",
",",
"'ORACLE_HOME'",
",",
"'TNS_ADMIN'",
",",
"'NLS_LANG'",
"]",
"result",
"=",
"{",
"}",
"for",
"env",
"in",
"envs",
":",
"if",
"env",
"in",
"os",
".",
"environ",
":",
"result",
"[",
"... | Show Environment used by Oracle Client
CLI Example:
.. code-block:: bash
salt '*' oracle.show_env
.. note::
at first _connect() ``NLS_LANG`` will forced to '.AL32UTF8' | [
"Show",
"Environment",
"used",
"by",
"Oracle",
"Client"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/oracle.py#L273-L291 | train |
saltstack/salt | salt/modules/solaris_user.py | _get_gecos | def _get_gecos(name):
'''
Retrieve GECOS field info and return it in dictionary form
'''
gecos_field = pwd.getpwnam(name).pw_gecos.split(',', 3)
if not gecos_field:
return {}
else:
# Assign empty strings for any unspecified trailing GECOS fields
while len(gecos_field) < 4:
gecos_field.append('')
return {'fullname': six.text_type(gecos_field[0]),
'roomnumber': six.text_type(gecos_field[1]),
'workphone': six.text_type(gecos_field[2]),
'homephone': six.text_type(gecos_field[3])} | python | def _get_gecos(name):
'''
Retrieve GECOS field info and return it in dictionary form
'''
gecos_field = pwd.getpwnam(name).pw_gecos.split(',', 3)
if not gecos_field:
return {}
else:
# Assign empty strings for any unspecified trailing GECOS fields
while len(gecos_field) < 4:
gecos_field.append('')
return {'fullname': six.text_type(gecos_field[0]),
'roomnumber': six.text_type(gecos_field[1]),
'workphone': six.text_type(gecos_field[2]),
'homephone': six.text_type(gecos_field[3])} | [
"def",
"_get_gecos",
"(",
"name",
")",
":",
"gecos_field",
"=",
"pwd",
".",
"getpwnam",
"(",
"name",
")",
".",
"pw_gecos",
".",
"split",
"(",
"','",
",",
"3",
")",
"if",
"not",
"gecos_field",
":",
"return",
"{",
"}",
"else",
":",
"# Assign empty string... | Retrieve GECOS field info and return it in dictionary form | [
"Retrieve",
"GECOS",
"field",
"info",
"and",
"return",
"it",
"in",
"dictionary",
"form"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_user.py#L46-L60 | train |
saltstack/salt | salt/modules/solaris_user.py | _build_gecos | def _build_gecos(gecos_dict):
'''
Accepts a dictionary entry containing GECOS field names and their values,
and returns a full GECOS comment string, to be used with usermod.
'''
return '{0},{1},{2},{3}'.format(gecos_dict.get('fullname', ''),
gecos_dict.get('roomnumber', ''),
gecos_dict.get('workphone', ''),
gecos_dict.get('homephone', '')) | python | def _build_gecos(gecos_dict):
'''
Accepts a dictionary entry containing GECOS field names and their values,
and returns a full GECOS comment string, to be used with usermod.
'''
return '{0},{1},{2},{3}'.format(gecos_dict.get('fullname', ''),
gecos_dict.get('roomnumber', ''),
gecos_dict.get('workphone', ''),
gecos_dict.get('homephone', '')) | [
"def",
"_build_gecos",
"(",
"gecos_dict",
")",
":",
"return",
"'{0},{1},{2},{3}'",
".",
"format",
"(",
"gecos_dict",
".",
"get",
"(",
"'fullname'",
",",
"''",
")",
",",
"gecos_dict",
".",
"get",
"(",
"'roomnumber'",
",",
"''",
")",
",",
"gecos_dict",
".",
... | Accepts a dictionary entry containing GECOS field names and their values,
and returns a full GECOS comment string, to be used with usermod. | [
"Accepts",
"a",
"dictionary",
"entry",
"containing",
"GECOS",
"field",
"names",
"and",
"their",
"values",
"and",
"returns",
"a",
"full",
"GECOS",
"comment",
"string",
"to",
"be",
"used",
"with",
"usermod",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_user.py#L63-L71 | train |
saltstack/salt | salt/modules/solaris_user.py | _update_gecos | def _update_gecos(name, key, value):
'''
Common code to change a user's GECOS information
'''
if not isinstance(value, six.string_types):
value = six.text_type(value)
pre_info = _get_gecos(name)
if not pre_info:
return False
if value == pre_info[key]:
return True
gecos_data = copy.deepcopy(pre_info)
gecos_data[key] = value
cmd = ['usermod', '-c', _build_gecos(gecos_data), name]
__salt__['cmd.run'](cmd, python_shell=False)
post_info = info(name)
return _get_gecos(name).get(key) == value | python | def _update_gecos(name, key, value):
'''
Common code to change a user's GECOS information
'''
if not isinstance(value, six.string_types):
value = six.text_type(value)
pre_info = _get_gecos(name)
if not pre_info:
return False
if value == pre_info[key]:
return True
gecos_data = copy.deepcopy(pre_info)
gecos_data[key] = value
cmd = ['usermod', '-c', _build_gecos(gecos_data), name]
__salt__['cmd.run'](cmd, python_shell=False)
post_info = info(name)
return _get_gecos(name).get(key) == value | [
"def",
"_update_gecos",
"(",
"name",
",",
"key",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"value",
"=",
"six",
".",
"text_type",
"(",
"value",
")",
"pre_info",
"=",
"_get_gecos",
"(",
... | Common code to change a user's GECOS information | [
"Common",
"code",
"to",
"change",
"a",
"user",
"s",
"GECOS",
"information"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_user.py#L74-L90 | train |
saltstack/salt | salt/modules/solaris_user.py | add | def add(name,
uid=None,
gid=None,
groups=None,
home=None,
shell=None,
unique=True,
fullname='',
roomnumber='',
workphone='',
homephone='',
createhome=True,
**kwargs):
'''
Add a user to the minion
CLI Example:
.. code-block:: bash
salt '*' user.add name <uid> <gid> <groups> <home> <shell>
'''
if salt.utils.data.is_true(kwargs.pop('system', False)):
log.warning('solaris_user module does not support the \'system\' '
'argument')
if kwargs:
log.warning('Invalid kwargs passed to user.add')
if isinstance(groups, six.string_types):
groups = groups.split(',')
cmd = ['useradd']
if shell:
cmd.extend(['-s', shell])
if uid:
cmd.extend(['-u', uid])
if gid:
cmd.extend(['-g', gid])
if groups:
cmd.extend(['-G', ','.join(groups)])
if createhome:
cmd.append('-m')
if home is not None:
cmd.extend(['-d', home])
if not unique:
cmd.append('-o')
cmd.append(name)
if __salt__['cmd.retcode'](cmd, python_shell=False) != 0:
return False
else:
# At this point, the user was successfully created, so return true
# regardless of the outcome of the below functions. If there is a
# problem wth changing any of the user's info below, it will be raised
# in a future highstate call. If anyone has a better idea on how to do
# this, feel free to change it, but I didn't think it was a good idea
# to return False when the user was successfully created since A) the
# user does exist, and B) running useradd again would result in a
# nonzero exit status and be interpreted as a False result.
if fullname:
chfullname(name, fullname)
if roomnumber:
chroomnumber(name, roomnumber)
if workphone:
chworkphone(name, workphone)
if homephone:
chhomephone(name, homephone)
return True | python | def add(name,
uid=None,
gid=None,
groups=None,
home=None,
shell=None,
unique=True,
fullname='',
roomnumber='',
workphone='',
homephone='',
createhome=True,
**kwargs):
'''
Add a user to the minion
CLI Example:
.. code-block:: bash
salt '*' user.add name <uid> <gid> <groups> <home> <shell>
'''
if salt.utils.data.is_true(kwargs.pop('system', False)):
log.warning('solaris_user module does not support the \'system\' '
'argument')
if kwargs:
log.warning('Invalid kwargs passed to user.add')
if isinstance(groups, six.string_types):
groups = groups.split(',')
cmd = ['useradd']
if shell:
cmd.extend(['-s', shell])
if uid:
cmd.extend(['-u', uid])
if gid:
cmd.extend(['-g', gid])
if groups:
cmd.extend(['-G', ','.join(groups)])
if createhome:
cmd.append('-m')
if home is not None:
cmd.extend(['-d', home])
if not unique:
cmd.append('-o')
cmd.append(name)
if __salt__['cmd.retcode'](cmd, python_shell=False) != 0:
return False
else:
# At this point, the user was successfully created, so return true
# regardless of the outcome of the below functions. If there is a
# problem wth changing any of the user's info below, it will be raised
# in a future highstate call. If anyone has a better idea on how to do
# this, feel free to change it, but I didn't think it was a good idea
# to return False when the user was successfully created since A) the
# user does exist, and B) running useradd again would result in a
# nonzero exit status and be interpreted as a False result.
if fullname:
chfullname(name, fullname)
if roomnumber:
chroomnumber(name, roomnumber)
if workphone:
chworkphone(name, workphone)
if homephone:
chhomephone(name, homephone)
return True | [
"def",
"add",
"(",
"name",
",",
"uid",
"=",
"None",
",",
"gid",
"=",
"None",
",",
"groups",
"=",
"None",
",",
"home",
"=",
"None",
",",
"shell",
"=",
"None",
",",
"unique",
"=",
"True",
",",
"fullname",
"=",
"''",
",",
"roomnumber",
"=",
"''",
... | Add a user to the minion
CLI Example:
.. code-block:: bash
salt '*' user.add name <uid> <gid> <groups> <home> <shell> | [
"Add",
"a",
"user",
"to",
"the",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_user.py#L93-L159 | train |
saltstack/salt | salt/modules/solaris_user.py | delete | def delete(name, remove=False, force=False):
'''
Remove a user from the minion
CLI Example:
.. code-block:: bash
salt '*' user.delete name remove=True force=True
'''
if salt.utils.data.is_true(force):
log.warning(
'userdel does not support force-deleting user while user is '
'logged in'
)
cmd = ['userdel']
if remove:
cmd.append('-r')
cmd.append(name)
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 | python | def delete(name, remove=False, force=False):
'''
Remove a user from the minion
CLI Example:
.. code-block:: bash
salt '*' user.delete name remove=True force=True
'''
if salt.utils.data.is_true(force):
log.warning(
'userdel does not support force-deleting user while user is '
'logged in'
)
cmd = ['userdel']
if remove:
cmd.append('-r')
cmd.append(name)
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 | [
"def",
"delete",
"(",
"name",
",",
"remove",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"if",
"salt",
".",
"utils",
".",
"data",
".",
"is_true",
"(",
"force",
")",
":",
"log",
".",
"warning",
"(",
"'userdel does not support force-deleting user whi... | Remove a user from the minion
CLI Example:
.. code-block:: bash
salt '*' user.delete name remove=True force=True | [
"Remove",
"a",
"user",
"from",
"the",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_user.py#L162-L181 | train |
saltstack/salt | salt/modules/solaris_user.py | chgid | def chgid(name, gid):
'''
Change the default group of the user
CLI Example:
.. code-block:: bash
salt '*' user.chgid foo 4376
'''
pre_info = info(name)
if not pre_info:
raise CommandExecutionError(
'User \'{0}\' does not exist'.format(name)
)
if gid == pre_info['gid']:
return True
cmd = ['usermod', '-g', gid, name]
__salt__['cmd.run'](cmd, python_shell=False)
return info(name).get('gid') == gid | python | def chgid(name, gid):
'''
Change the default group of the user
CLI Example:
.. code-block:: bash
salt '*' user.chgid foo 4376
'''
pre_info = info(name)
if not pre_info:
raise CommandExecutionError(
'User \'{0}\' does not exist'.format(name)
)
if gid == pre_info['gid']:
return True
cmd = ['usermod', '-g', gid, name]
__salt__['cmd.run'](cmd, python_shell=False)
return info(name).get('gid') == gid | [
"def",
"chgid",
"(",
"name",
",",
"gid",
")",
":",
"pre_info",
"=",
"info",
"(",
"name",
")",
"if",
"not",
"pre_info",
":",
"raise",
"CommandExecutionError",
"(",
"'User \\'{0}\\' does not exist'",
".",
"format",
"(",
"name",
")",
")",
"if",
"gid",
"==",
... | Change the default group of the user
CLI Example:
.. code-block:: bash
salt '*' user.chgid foo 4376 | [
"Change",
"the",
"default",
"group",
"of",
"the",
"user"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_user.py#L226-L245 | train |
saltstack/salt | salt/modules/solaris_user.py | chshell | def chshell(name, shell):
'''
Change the default shell of the user
CLI Example:
.. code-block:: bash
salt '*' user.chshell foo /bin/zsh
'''
pre_info = info(name)
if not pre_info:
raise CommandExecutionError(
'User \'{0}\' does not exist'.format(name)
)
if shell == pre_info['shell']:
return True
cmd = ['usermod', '-s', shell, name]
__salt__['cmd.run'](cmd, python_shell=False)
return info(name).get('shell') == shell | python | def chshell(name, shell):
'''
Change the default shell of the user
CLI Example:
.. code-block:: bash
salt '*' user.chshell foo /bin/zsh
'''
pre_info = info(name)
if not pre_info:
raise CommandExecutionError(
'User \'{0}\' does not exist'.format(name)
)
if shell == pre_info['shell']:
return True
cmd = ['usermod', '-s', shell, name]
__salt__['cmd.run'](cmd, python_shell=False)
return info(name).get('shell') == shell | [
"def",
"chshell",
"(",
"name",
",",
"shell",
")",
":",
"pre_info",
"=",
"info",
"(",
"name",
")",
"if",
"not",
"pre_info",
":",
"raise",
"CommandExecutionError",
"(",
"'User \\'{0}\\' does not exist'",
".",
"format",
"(",
"name",
")",
")",
"if",
"shell",
"... | Change the default shell of the user
CLI Example:
.. code-block:: bash
salt '*' user.chshell foo /bin/zsh | [
"Change",
"the",
"default",
"shell",
"of",
"the",
"user"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_user.py#L248-L267 | train |
saltstack/salt | salt/modules/solaris_user.py | chhome | def chhome(name, home, persist=False):
'''
Set a new home directory for an existing user
name
Username to modify
home
New home directory to set
persist : False
Set to ``True`` to prevent configuration files in the new home
directory from being overwritten by the files from the skeleton
directory.
CLI Example:
.. code-block:: bash
salt '*' user.chhome foo /home/users/foo True
'''
pre_info = info(name)
if not pre_info:
raise CommandExecutionError(
'User \'{0}\' does not exist'.format(name)
)
if home == pre_info['home']:
return True
cmd = ['usermod', '-d', home]
if persist:
cmd.append('-m')
cmd.append(name)
__salt__['cmd.run'](cmd, python_shell=False)
return info(name).get('home') == home | python | def chhome(name, home, persist=False):
'''
Set a new home directory for an existing user
name
Username to modify
home
New home directory to set
persist : False
Set to ``True`` to prevent configuration files in the new home
directory from being overwritten by the files from the skeleton
directory.
CLI Example:
.. code-block:: bash
salt '*' user.chhome foo /home/users/foo True
'''
pre_info = info(name)
if not pre_info:
raise CommandExecutionError(
'User \'{0}\' does not exist'.format(name)
)
if home == pre_info['home']:
return True
cmd = ['usermod', '-d', home]
if persist:
cmd.append('-m')
cmd.append(name)
__salt__['cmd.run'](cmd, python_shell=False)
return info(name).get('home') == home | [
"def",
"chhome",
"(",
"name",
",",
"home",
",",
"persist",
"=",
"False",
")",
":",
"pre_info",
"=",
"info",
"(",
"name",
")",
"if",
"not",
"pre_info",
":",
"raise",
"CommandExecutionError",
"(",
"'User \\'{0}\\' does not exist'",
".",
"format",
"(",
"name",
... | Set a new home directory for an existing user
name
Username to modify
home
New home directory to set
persist : False
Set to ``True`` to prevent configuration files in the new home
directory from being overwritten by the files from the skeleton
directory.
CLI Example:
.. code-block:: bash
salt '*' user.chhome foo /home/users/foo True | [
"Set",
"a",
"new",
"home",
"directory",
"for",
"an",
"existing",
"user"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_user.py#L270-L303 | train |
saltstack/salt | salt/modules/solaris_user.py | chgroups | def chgroups(name, groups, append=False):
'''
Change the groups to which a user belongs
name
Username to modify
groups
List of groups to set for the user. Can be passed as a comma-separated
list or a Python list.
append : False
Set to ``True`` to append these groups to the user's existing list of
groups. Otherwise, the specified groups will replace any existing
groups for the user.
CLI Example:
.. code-block:: bash
salt '*' user.chgroups foo wheel,root True
'''
if isinstance(groups, six.string_types):
groups = groups.split(',')
ugrps = set(list_groups(name))
if ugrps == set(groups):
return True
if append:
groups.update(ugrps)
cmd = ['usermod', '-G', ','.join(groups), name]
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 | python | def chgroups(name, groups, append=False):
'''
Change the groups to which a user belongs
name
Username to modify
groups
List of groups to set for the user. Can be passed as a comma-separated
list or a Python list.
append : False
Set to ``True`` to append these groups to the user's existing list of
groups. Otherwise, the specified groups will replace any existing
groups for the user.
CLI Example:
.. code-block:: bash
salt '*' user.chgroups foo wheel,root True
'''
if isinstance(groups, six.string_types):
groups = groups.split(',')
ugrps = set(list_groups(name))
if ugrps == set(groups):
return True
if append:
groups.update(ugrps)
cmd = ['usermod', '-G', ','.join(groups), name]
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0 | [
"def",
"chgroups",
"(",
"name",
",",
"groups",
",",
"append",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"groups",
",",
"six",
".",
"string_types",
")",
":",
"groups",
"=",
"groups",
".",
"split",
"(",
"','",
")",
"ugrps",
"=",
"set",
"(",
"l... | Change the groups to which a user belongs
name
Username to modify
groups
List of groups to set for the user. Can be passed as a comma-separated
list or a Python list.
append : False
Set to ``True`` to append these groups to the user's existing list of
groups. Otherwise, the specified groups will replace any existing
groups for the user.
CLI Example:
.. code-block:: bash
salt '*' user.chgroups foo wheel,root True | [
"Change",
"the",
"groups",
"to",
"which",
"a",
"user",
"belongs"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_user.py#L306-L336 | train |
saltstack/salt | salt/modules/solaris_user.py | rename | def rename(name, new_name):
'''
Change the username for a named user
CLI Example:
.. code-block:: bash
salt '*' user.rename name new_name
'''
current_info = info(name)
if not current_info:
raise CommandExecutionError('User \'{0}\' does not exist'.format(name))
new_info = info(new_name)
if new_info:
raise CommandExecutionError(
'User \'{0}\' already exists'.format(new_name)
)
cmd = ['usermod', '-l', new_name, name]
__salt__['cmd.run'](cmd, python_shell=False)
return info(new_name).get('name') == new_name | python | def rename(name, new_name):
'''
Change the username for a named user
CLI Example:
.. code-block:: bash
salt '*' user.rename name new_name
'''
current_info = info(name)
if not current_info:
raise CommandExecutionError('User \'{0}\' does not exist'.format(name))
new_info = info(new_name)
if new_info:
raise CommandExecutionError(
'User \'{0}\' already exists'.format(new_name)
)
cmd = ['usermod', '-l', new_name, name]
__salt__['cmd.run'](cmd, python_shell=False)
return info(new_name).get('name') == new_name | [
"def",
"rename",
"(",
"name",
",",
"new_name",
")",
":",
"current_info",
"=",
"info",
"(",
"name",
")",
"if",
"not",
"current_info",
":",
"raise",
"CommandExecutionError",
"(",
"'User \\'{0}\\' does not exist'",
".",
"format",
"(",
"name",
")",
")",
"new_info"... | Change the username for a named user
CLI Example:
.. code-block:: bash
salt '*' user.rename name new_name | [
"Change",
"the",
"username",
"for",
"a",
"named",
"user"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_user.py#L451-L471 | train |
saltstack/salt | salt/utils/virtualbox.py | vb_get_manager | def vb_get_manager():
'''
Creates a 'singleton' manager to communicate with a local virtualbox hypervisor.
@return:
@rtype: VirtualBoxManager
'''
global _virtualboxManager
if _virtualboxManager is None and HAS_LIBS:
salt.utils.compat.reload(vboxapi)
_virtualboxManager = vboxapi.VirtualBoxManager(None, None)
return _virtualboxManager | python | def vb_get_manager():
'''
Creates a 'singleton' manager to communicate with a local virtualbox hypervisor.
@return:
@rtype: VirtualBoxManager
'''
global _virtualboxManager
if _virtualboxManager is None and HAS_LIBS:
salt.utils.compat.reload(vboxapi)
_virtualboxManager = vboxapi.VirtualBoxManager(None, None)
return _virtualboxManager | [
"def",
"vb_get_manager",
"(",
")",
":",
"global",
"_virtualboxManager",
"if",
"_virtualboxManager",
"is",
"None",
"and",
"HAS_LIBS",
":",
"salt",
".",
"utils",
".",
"compat",
".",
"reload",
"(",
"vboxapi",
")",
"_virtualboxManager",
"=",
"vboxapi",
".",
"Virtu... | Creates a 'singleton' manager to communicate with a local virtualbox hypervisor.
@return:
@rtype: VirtualBoxManager | [
"Creates",
"a",
"singleton",
"manager",
"to",
"communicate",
"with",
"a",
"local",
"virtualbox",
"hypervisor",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/virtualbox.py#L133-L144 | train |
saltstack/salt | salt/utils/virtualbox.py | vb_get_box | def vb_get_box():
'''
Needed for certain operations in the SDK e.g creating sessions
@return:
@rtype: IVirtualBox
'''
vb_get_manager()
try:
# This works in older versions of the SDK, but does not seem to work anymore.
vbox = _virtualboxManager.vbox
except AttributeError:
vbox = _virtualboxManager.getVirtualBox()
return vbox | python | def vb_get_box():
'''
Needed for certain operations in the SDK e.g creating sessions
@return:
@rtype: IVirtualBox
'''
vb_get_manager()
try:
# This works in older versions of the SDK, but does not seem to work anymore.
vbox = _virtualboxManager.vbox
except AttributeError:
vbox = _virtualboxManager.getVirtualBox()
return vbox | [
"def",
"vb_get_box",
"(",
")",
":",
"vb_get_manager",
"(",
")",
"try",
":",
"# This works in older versions of the SDK, but does not seem to work anymore.",
"vbox",
"=",
"_virtualboxManager",
".",
"vbox",
"except",
"AttributeError",
":",
"vbox",
"=",
"_virtualboxManager",
... | Needed for certain operations in the SDK e.g creating sessions
@return:
@rtype: IVirtualBox | [
"Needed",
"for",
"certain",
"operations",
"in",
"the",
"SDK",
"e",
".",
"g",
"creating",
"sessions"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/virtualbox.py#L147-L161 | train |
saltstack/salt | salt/utils/virtualbox.py | vb_get_max_network_slots | def vb_get_max_network_slots():
'''
Max number of slots any machine can have
@return:
@rtype: number
'''
sysprops = vb_get_box().systemProperties
totals = [
sysprops.getMaxNetworkAdapters(adapter_type)
for adapter_type in [
1, # PIIX3 A PIIX3 (PCI IDE ISA Xcelerator) chipset.
2 # ICH9 A ICH9 (I/O Controller Hub) chipset
]
]
return sum(totals) | python | def vb_get_max_network_slots():
'''
Max number of slots any machine can have
@return:
@rtype: number
'''
sysprops = vb_get_box().systemProperties
totals = [
sysprops.getMaxNetworkAdapters(adapter_type)
for adapter_type in [
1, # PIIX3 A PIIX3 (PCI IDE ISA Xcelerator) chipset.
2 # ICH9 A ICH9 (I/O Controller Hub) chipset
]
]
return sum(totals) | [
"def",
"vb_get_max_network_slots",
"(",
")",
":",
"sysprops",
"=",
"vb_get_box",
"(",
")",
".",
"systemProperties",
"totals",
"=",
"[",
"sysprops",
".",
"getMaxNetworkAdapters",
"(",
"adapter_type",
")",
"for",
"adapter_type",
"in",
"[",
"1",
",",
"# PIIX3 A PII... | Max number of slots any machine can have
@return:
@rtype: number | [
"Max",
"number",
"of",
"slots",
"any",
"machine",
"can",
"have"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/virtualbox.py#L164-L178 | train |
saltstack/salt | salt/utils/virtualbox.py | vb_get_network_adapters | def vb_get_network_adapters(machine_name=None, machine=None):
'''
A valid machine_name or a machine is needed to make this work!
@param machine_name:
@type machine_name: str
@param machine:
@type machine: IMachine
@return: INetorkAdapter's converted to dicts
@rtype: [dict]
'''
if machine_name:
machine = vb_get_box().findMachine(machine_name)
network_adapters = []
for i in range(vb_get_max_network_slots()):
try:
inetwork_adapter = machine.getNetworkAdapter(i)
network_adapter = vb_xpcom_to_attribute_dict(
inetwork_adapter, 'INetworkAdapter'
)
network_adapter['properties'] = inetwork_adapter.getProperties('')
network_adapters.append(network_adapter)
except Exception:
pass
return network_adapters | python | def vb_get_network_adapters(machine_name=None, machine=None):
'''
A valid machine_name or a machine is needed to make this work!
@param machine_name:
@type machine_name: str
@param machine:
@type machine: IMachine
@return: INetorkAdapter's converted to dicts
@rtype: [dict]
'''
if machine_name:
machine = vb_get_box().findMachine(machine_name)
network_adapters = []
for i in range(vb_get_max_network_slots()):
try:
inetwork_adapter = machine.getNetworkAdapter(i)
network_adapter = vb_xpcom_to_attribute_dict(
inetwork_adapter, 'INetworkAdapter'
)
network_adapter['properties'] = inetwork_adapter.getProperties('')
network_adapters.append(network_adapter)
except Exception:
pass
return network_adapters | [
"def",
"vb_get_network_adapters",
"(",
"machine_name",
"=",
"None",
",",
"machine",
"=",
"None",
")",
":",
"if",
"machine_name",
":",
"machine",
"=",
"vb_get_box",
"(",
")",
".",
"findMachine",
"(",
"machine_name",
")",
"network_adapters",
"=",
"[",
"]",
"fo... | A valid machine_name or a machine is needed to make this work!
@param machine_name:
@type machine_name: str
@param machine:
@type machine: IMachine
@return: INetorkAdapter's converted to dicts
@rtype: [dict] | [
"A",
"valid",
"machine_name",
"or",
"a",
"machine",
"is",
"needed",
"to",
"make",
"this",
"work!"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/virtualbox.py#L181-L208 | train |
saltstack/salt | salt/utils/virtualbox.py | vb_wait_for_network_address | def vb_wait_for_network_address(timeout, step=None, machine_name=None, machine=None, wait_for_pattern=None):
'''
Wait until a machine has a network address to return or quit after the timeout
@param timeout: in seconds
@type timeout: float
@param step: How regularly we want to check for ips (in seconds)
@type step: float
@param machine_name:
@type machine_name: str
@param machine:
@type machine: IMachine
@type wait_for_pattern: str
@param wait_for_pattern:
@type machine: str
@return:
@rtype: list
'''
kwargs = {
'machine_name': machine_name,
'machine': machine,
'wait_for_pattern': wait_for_pattern
}
return wait_for(vb_get_network_addresses, timeout=timeout, step=step, default=[], func_kwargs=kwargs) | python | def vb_wait_for_network_address(timeout, step=None, machine_name=None, machine=None, wait_for_pattern=None):
'''
Wait until a machine has a network address to return or quit after the timeout
@param timeout: in seconds
@type timeout: float
@param step: How regularly we want to check for ips (in seconds)
@type step: float
@param machine_name:
@type machine_name: str
@param machine:
@type machine: IMachine
@type wait_for_pattern: str
@param wait_for_pattern:
@type machine: str
@return:
@rtype: list
'''
kwargs = {
'machine_name': machine_name,
'machine': machine,
'wait_for_pattern': wait_for_pattern
}
return wait_for(vb_get_network_addresses, timeout=timeout, step=step, default=[], func_kwargs=kwargs) | [
"def",
"vb_wait_for_network_address",
"(",
"timeout",
",",
"step",
"=",
"None",
",",
"machine_name",
"=",
"None",
",",
"machine",
"=",
"None",
",",
"wait_for_pattern",
"=",
"None",
")",
":",
"kwargs",
"=",
"{",
"'machine_name'",
":",
"machine_name",
",",
"'m... | Wait until a machine has a network address to return or quit after the timeout
@param timeout: in seconds
@type timeout: float
@param step: How regularly we want to check for ips (in seconds)
@type step: float
@param machine_name:
@type machine_name: str
@param machine:
@type machine: IMachine
@type wait_for_pattern: str
@param wait_for_pattern:
@type machine: str
@return:
@rtype: list | [
"Wait",
"until",
"a",
"machine",
"has",
"a",
"network",
"address",
"to",
"return",
"or",
"quit",
"after",
"the",
"timeout"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/virtualbox.py#L211-L234 | train |
saltstack/salt | salt/utils/virtualbox.py | vb_wait_for_session_state | def vb_wait_for_session_state(xp_session, state='Unlocked', timeout=10, step=None):
'''
Waits until a session state has been reached, checking at regular intervals.
@param xp_session:
@type xp_session: ISession from the Virtualbox API
@param state: The constant descriptor according to the docs
@type state: str
@param timeout: in seconds
@type timeout: int | float
@param step: Intervals at which the value is checked
@type step: int | float
@return: Did we reach the state?
@rtype: bool
'''
args = (xp_session, state)
wait_for(_check_session_state, timeout=timeout, step=step, default=False, func_args=args) | python | def vb_wait_for_session_state(xp_session, state='Unlocked', timeout=10, step=None):
'''
Waits until a session state has been reached, checking at regular intervals.
@param xp_session:
@type xp_session: ISession from the Virtualbox API
@param state: The constant descriptor according to the docs
@type state: str
@param timeout: in seconds
@type timeout: int | float
@param step: Intervals at which the value is checked
@type step: int | float
@return: Did we reach the state?
@rtype: bool
'''
args = (xp_session, state)
wait_for(_check_session_state, timeout=timeout, step=step, default=False, func_args=args) | [
"def",
"vb_wait_for_session_state",
"(",
"xp_session",
",",
"state",
"=",
"'Unlocked'",
",",
"timeout",
"=",
"10",
",",
"step",
"=",
"None",
")",
":",
"args",
"=",
"(",
"xp_session",
",",
"state",
")",
"wait_for",
"(",
"_check_session_state",
",",
"timeout",... | Waits until a session state has been reached, checking at regular intervals.
@param xp_session:
@type xp_session: ISession from the Virtualbox API
@param state: The constant descriptor according to the docs
@type state: str
@param timeout: in seconds
@type timeout: int | float
@param step: Intervals at which the value is checked
@type step: int | float
@return: Did we reach the state?
@rtype: bool | [
"Waits",
"until",
"a",
"session",
"state",
"has",
"been",
"reached",
"checking",
"at",
"regular",
"intervals",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/virtualbox.py#L250-L266 | train |
saltstack/salt | salt/utils/virtualbox.py | vb_get_network_addresses | def vb_get_network_addresses(machine_name=None, machine=None, wait_for_pattern=None):
'''
TODO distinguish between private and public addresses
A valid machine_name or a machine is needed to make this work!
!!!
Guest prerequisite: GuestAddition
!!!
Thanks to Shrikant Havale for the StackOverflow answer http://stackoverflow.com/a/29335390
More information on guest properties: https://www.virtualbox.org/manual/ch04.html#guestadd-guestprops
@param machine_name:
@type machine_name: str
@param machine:
@type machine: IMachine
@return: All the IPv4 addresses we could get
@rtype: str[]
'''
if machine_name:
machine = vb_get_box().findMachine(machine_name)
ip_addresses = []
log.debug("checking for power on:")
if machine.state == _virtualboxManager.constants.MachineState_Running:
log.debug("got power on:")
#wait on an arbitrary named property
#for instance use a dhcp client script to set a property via VBoxControl guestproperty set dhcp_done 1
if wait_for_pattern and not machine.getGuestPropertyValue(wait_for_pattern):
log.debug("waiting for pattern:%s:", wait_for_pattern)
return None
_total_slots = machine.getGuestPropertyValue('/VirtualBox/GuestInfo/Net/Count')
#upon dhcp the net count drops to 0 and it takes some seconds for it to be set again
if not _total_slots:
log.debug("waiting for net count:%s:", wait_for_pattern)
return None
try:
total_slots = int(_total_slots)
for i in range(total_slots):
try:
address = machine.getGuestPropertyValue('/VirtualBox/GuestInfo/Net/{0}/V4/IP'.format(i))
if address:
ip_addresses.append(address)
except Exception as e:
log.debug(e.message)
except ValueError as e:
log.debug(e.message)
return None
log.debug("returning ip_addresses:%s:", ip_addresses)
return ip_addresses | python | def vb_get_network_addresses(machine_name=None, machine=None, wait_for_pattern=None):
'''
TODO distinguish between private and public addresses
A valid machine_name or a machine is needed to make this work!
!!!
Guest prerequisite: GuestAddition
!!!
Thanks to Shrikant Havale for the StackOverflow answer http://stackoverflow.com/a/29335390
More information on guest properties: https://www.virtualbox.org/manual/ch04.html#guestadd-guestprops
@param machine_name:
@type machine_name: str
@param machine:
@type machine: IMachine
@return: All the IPv4 addresses we could get
@rtype: str[]
'''
if machine_name:
machine = vb_get_box().findMachine(machine_name)
ip_addresses = []
log.debug("checking for power on:")
if machine.state == _virtualboxManager.constants.MachineState_Running:
log.debug("got power on:")
#wait on an arbitrary named property
#for instance use a dhcp client script to set a property via VBoxControl guestproperty set dhcp_done 1
if wait_for_pattern and not machine.getGuestPropertyValue(wait_for_pattern):
log.debug("waiting for pattern:%s:", wait_for_pattern)
return None
_total_slots = machine.getGuestPropertyValue('/VirtualBox/GuestInfo/Net/Count')
#upon dhcp the net count drops to 0 and it takes some seconds for it to be set again
if not _total_slots:
log.debug("waiting for net count:%s:", wait_for_pattern)
return None
try:
total_slots = int(_total_slots)
for i in range(total_slots):
try:
address = machine.getGuestPropertyValue('/VirtualBox/GuestInfo/Net/{0}/V4/IP'.format(i))
if address:
ip_addresses.append(address)
except Exception as e:
log.debug(e.message)
except ValueError as e:
log.debug(e.message)
return None
log.debug("returning ip_addresses:%s:", ip_addresses)
return ip_addresses | [
"def",
"vb_get_network_addresses",
"(",
"machine_name",
"=",
"None",
",",
"machine",
"=",
"None",
",",
"wait_for_pattern",
"=",
"None",
")",
":",
"if",
"machine_name",
":",
"machine",
"=",
"vb_get_box",
"(",
")",
".",
"findMachine",
"(",
"machine_name",
")",
... | TODO distinguish between private and public addresses
A valid machine_name or a machine is needed to make this work!
!!!
Guest prerequisite: GuestAddition
!!!
Thanks to Shrikant Havale for the StackOverflow answer http://stackoverflow.com/a/29335390
More information on guest properties: https://www.virtualbox.org/manual/ch04.html#guestadd-guestprops
@param machine_name:
@type machine_name: str
@param machine:
@type machine: IMachine
@return: All the IPv4 addresses we could get
@rtype: str[] | [
"TODO",
"distinguish",
"between",
"private",
"and",
"public",
"addresses"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/virtualbox.py#L269-L326 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.