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/thorium/status.py | reg | def reg(name):
'''
Activate this register to turn on a minion status tracking register, this
register keeps the current status beacon data and the time that each beacon
was last checked in.
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': True}
now = time.time()
if 'status' not in __reg__:
__reg__['status'] = {}
__reg__['status']['val'] = {}
for event in __events__:
if fnmatch.fnmatch(event['tag'], 'salt/beacon/*/status/*'):
# Got one!
idata = {'recv_time': now}
for key in event['data']['data']:
if key in ('id', 'recv_time'):
continue
idata[key] = event['data']['data'][key]
__reg__['status']['val'][event['data']['id']] = idata
ret['changes'][event['data']['id']] = True
return ret | python | def reg(name):
'''
Activate this register to turn on a minion status tracking register, this
register keeps the current status beacon data and the time that each beacon
was last checked in.
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': True}
now = time.time()
if 'status' not in __reg__:
__reg__['status'] = {}
__reg__['status']['val'] = {}
for event in __events__:
if fnmatch.fnmatch(event['tag'], 'salt/beacon/*/status/*'):
# Got one!
idata = {'recv_time': now}
for key in event['data']['data']:
if key in ('id', 'recv_time'):
continue
idata[key] = event['data']['data'][key]
__reg__['status']['val'][event['data']['id']] = idata
ret['changes'][event['data']['id']] = True
return ret | [
"def",
"reg",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
",",
"'result'",
":",
"True",
"}",
"now",
"=",
"time",
".",
"time",
"(",
")",
"if",
"'status'",
"not",
"i... | Activate this register to turn on a minion status tracking register, this
register keeps the current status beacon data and the time that each beacon
was last checked in. | [
"Activate",
"this",
"register",
"to",
"turn",
"on",
"a",
"minion",
"status",
"tracking",
"register",
"this",
"register",
"keeps",
"the",
"current",
"status",
"beacon",
"data",
"and",
"the",
"time",
"that",
"each",
"beacon",
"was",
"last",
"checked",
"in",
".... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/status.py#L14-L38 | train |
saltstack/salt | salt/tops/reclass_adapter.py | top | def top(**kwargs):
'''
Query |reclass| for the top data (states of the minions).
'''
# If reclass is installed, __virtual__ put it onto the search path, so we
# don't need to protect against ImportError:
# pylint: disable=3rd-party-module-not-gated
from reclass.adapters.salt import top as reclass_top
from reclass.errors import ReclassException
# pylint: enable=3rd-party-module-not-gated
try:
# Salt's top interface is inconsistent with ext_pillar (see #5786) and
# one is expected to extract the arguments to the master_tops plugin
# by parsing the configuration file data. I therefore use this adapter
# to hide this internality.
reclass_opts = __opts__['master_tops']['reclass']
# the source path we used above isn't something reclass needs to care
# about, so filter it:
filter_out_source_path_option(reclass_opts)
# if no inventory_base_uri was specified, initialise it to the first
# file_roots of class 'base' (if that exists):
set_inventory_base_uri_default(__opts__, kwargs)
# Salt expects the top data to be filtered by minion_id, so we better
# let it know which minion it is dealing with. Unfortunately, we must
# extract these data (see #6930):
minion_id = kwargs['opts']['id']
# I purposely do not pass any of __opts__ or __salt__ or __grains__
# to reclass, as I consider those to be Salt-internal and reclass
# should not make any assumptions about it. Reclass only needs to know
# how it's configured, so:
return reclass_top(minion_id, **reclass_opts)
except ImportError as e:
if 'reclass' in six.text_type(e):
raise SaltInvocationError(
'master_tops.reclass: cannot find reclass module '
'in {0}'.format(sys.path)
)
else:
raise
except TypeError as e:
if 'unexpected keyword argument' in six.text_type(e):
arg = six.text_type(e).split()[-1]
raise SaltInvocationError(
'master_tops.reclass: unexpected option: {0}'.format(arg)
)
else:
raise
except KeyError as e:
if 'reclass' in six.text_type(e):
raise SaltInvocationError('master_tops.reclass: no configuration '
'found in master config')
else:
raise
except ReclassException as e:
raise SaltInvocationError('master_tops.reclass: {0}'.format(six.text_type(e))) | python | def top(**kwargs):
'''
Query |reclass| for the top data (states of the minions).
'''
# If reclass is installed, __virtual__ put it onto the search path, so we
# don't need to protect against ImportError:
# pylint: disable=3rd-party-module-not-gated
from reclass.adapters.salt import top as reclass_top
from reclass.errors import ReclassException
# pylint: enable=3rd-party-module-not-gated
try:
# Salt's top interface is inconsistent with ext_pillar (see #5786) and
# one is expected to extract the arguments to the master_tops plugin
# by parsing the configuration file data. I therefore use this adapter
# to hide this internality.
reclass_opts = __opts__['master_tops']['reclass']
# the source path we used above isn't something reclass needs to care
# about, so filter it:
filter_out_source_path_option(reclass_opts)
# if no inventory_base_uri was specified, initialise it to the first
# file_roots of class 'base' (if that exists):
set_inventory_base_uri_default(__opts__, kwargs)
# Salt expects the top data to be filtered by minion_id, so we better
# let it know which minion it is dealing with. Unfortunately, we must
# extract these data (see #6930):
minion_id = kwargs['opts']['id']
# I purposely do not pass any of __opts__ or __salt__ or __grains__
# to reclass, as I consider those to be Salt-internal and reclass
# should not make any assumptions about it. Reclass only needs to know
# how it's configured, so:
return reclass_top(minion_id, **reclass_opts)
except ImportError as e:
if 'reclass' in six.text_type(e):
raise SaltInvocationError(
'master_tops.reclass: cannot find reclass module '
'in {0}'.format(sys.path)
)
else:
raise
except TypeError as e:
if 'unexpected keyword argument' in six.text_type(e):
arg = six.text_type(e).split()[-1]
raise SaltInvocationError(
'master_tops.reclass: unexpected option: {0}'.format(arg)
)
else:
raise
except KeyError as e:
if 'reclass' in six.text_type(e):
raise SaltInvocationError('master_tops.reclass: no configuration '
'found in master config')
else:
raise
except ReclassException as e:
raise SaltInvocationError('master_tops.reclass: {0}'.format(six.text_type(e))) | [
"def",
"top",
"(",
"*",
"*",
"kwargs",
")",
":",
"# If reclass is installed, __virtual__ put it onto the search path, so we",
"# don't need to protect against ImportError:",
"# pylint: disable=3rd-party-module-not-gated",
"from",
"reclass",
".",
"adapters",
".",
"salt",
"import",
... | Query |reclass| for the top data (states of the minions). | [
"Query",
"|reclass|",
"for",
"the",
"top",
"data",
"(",
"states",
"of",
"the",
"minions",
")",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/tops/reclass_adapter.py#L82-L146 | train |
saltstack/salt | salt/modules/boto_datapipeline.py | create_pipeline | def create_pipeline(name, unique_id, description='', region=None, key=None, keyid=None,
profile=None):
'''
Create a new, empty pipeline. This function is idempotent.
CLI example:
.. code-block:: bash
salt myminion boto_datapipeline.create_pipeline my_name my_unique_id
'''
client = _get_client(region, key, keyid, profile)
r = {}
try:
response = client.create_pipeline(
name=name,
uniqueId=unique_id,
description=description,
)
r['result'] = response['pipelineId']
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
r['error'] = six.text_type(e)
return r | python | def create_pipeline(name, unique_id, description='', region=None, key=None, keyid=None,
profile=None):
'''
Create a new, empty pipeline. This function is idempotent.
CLI example:
.. code-block:: bash
salt myminion boto_datapipeline.create_pipeline my_name my_unique_id
'''
client = _get_client(region, key, keyid, profile)
r = {}
try:
response = client.create_pipeline(
name=name,
uniqueId=unique_id,
description=description,
)
r['result'] = response['pipelineId']
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
r['error'] = six.text_type(e)
return r | [
"def",
"create_pipeline",
"(",
"name",
",",
"unique_id",
",",
"description",
"=",
"''",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"client",
"=",
"_get_client",
"(",
"region",
... | Create a new, empty pipeline. This function is idempotent.
CLI example:
.. code-block:: bash
salt myminion boto_datapipeline.create_pipeline my_name my_unique_id | [
"Create",
"a",
"new",
"empty",
"pipeline",
".",
"This",
"function",
"is",
"idempotent",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_datapipeline.py#L57-L79 | train |
saltstack/salt | salt/modules/boto_datapipeline.py | delete_pipeline | def delete_pipeline(pipeline_id, region=None, key=None, keyid=None, profile=None):
'''
Delete a pipeline, its pipeline definition, and its run history. This function is idempotent.
CLI example:
.. code-block:: bash
salt myminion boto_datapipeline.delete_pipeline my_pipeline_id
'''
client = _get_client(region, key, keyid, profile)
r = {}
try:
client.delete_pipeline(pipelineId=pipeline_id)
r['result'] = True
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
r['error'] = six.text_type(e)
return r | python | def delete_pipeline(pipeline_id, region=None, key=None, keyid=None, profile=None):
'''
Delete a pipeline, its pipeline definition, and its run history. This function is idempotent.
CLI example:
.. code-block:: bash
salt myminion boto_datapipeline.delete_pipeline my_pipeline_id
'''
client = _get_client(region, key, keyid, profile)
r = {}
try:
client.delete_pipeline(pipelineId=pipeline_id)
r['result'] = True
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
r['error'] = six.text_type(e)
return r | [
"def",
"delete_pipeline",
"(",
"pipeline_id",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"client",
"=",
"_get_client",
"(",
"region",
",",
"key",
",",
"keyid",
",",
"profile",
... | Delete a pipeline, its pipeline definition, and its run history. This function is idempotent.
CLI example:
.. code-block:: bash
salt myminion boto_datapipeline.delete_pipeline my_pipeline_id | [
"Delete",
"a",
"pipeline",
"its",
"pipeline",
"definition",
"and",
"its",
"run",
"history",
".",
"This",
"function",
"is",
"idempotent",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_datapipeline.py#L82-L99 | train |
saltstack/salt | salt/modules/boto_datapipeline.py | describe_pipelines | def describe_pipelines(pipeline_ids, region=None, key=None, keyid=None, profile=None):
'''
Retrieve metadata about one or more pipelines.
CLI example:
.. code-block:: bash
salt myminion boto_datapipeline.describe_pipelines ['my_pipeline_id']
'''
client = _get_client(region, key, keyid, profile)
r = {}
try:
r['result'] = client.describe_pipelines(pipelineIds=pipeline_ids)
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
r['error'] = six.text_type(e)
return r | python | def describe_pipelines(pipeline_ids, region=None, key=None, keyid=None, profile=None):
'''
Retrieve metadata about one or more pipelines.
CLI example:
.. code-block:: bash
salt myminion boto_datapipeline.describe_pipelines ['my_pipeline_id']
'''
client = _get_client(region, key, keyid, profile)
r = {}
try:
r['result'] = client.describe_pipelines(pipelineIds=pipeline_ids)
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
r['error'] = six.text_type(e)
return r | [
"def",
"describe_pipelines",
"(",
"pipeline_ids",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"client",
"=",
"_get_client",
"(",
"region",
",",
"key",
",",
"keyid",
",",
"profil... | Retrieve metadata about one or more pipelines.
CLI example:
.. code-block:: bash
salt myminion boto_datapipeline.describe_pipelines ['my_pipeline_id'] | [
"Retrieve",
"metadata",
"about",
"one",
"or",
"more",
"pipelines",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_datapipeline.py#L102-L118 | train |
saltstack/salt | salt/modules/boto_datapipeline.py | list_pipelines | def list_pipelines(region=None, key=None, keyid=None, profile=None):
'''
Get a list of pipeline ids and names for all pipelines.
CLI Example:
.. code-block:: bash
salt myminion boto_datapipeline.list_pipelines profile=myprofile
'''
client = _get_client(region, key, keyid, profile)
r = {}
try:
paginator = client.get_paginator('list_pipelines')
pipelines = []
for page in paginator.paginate():
pipelines += page['pipelineIdList']
r['result'] = pipelines
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
r['error'] = six.text_type(e)
return r | python | def list_pipelines(region=None, key=None, keyid=None, profile=None):
'''
Get a list of pipeline ids and names for all pipelines.
CLI Example:
.. code-block:: bash
salt myminion boto_datapipeline.list_pipelines profile=myprofile
'''
client = _get_client(region, key, keyid, profile)
r = {}
try:
paginator = client.get_paginator('list_pipelines')
pipelines = []
for page in paginator.paginate():
pipelines += page['pipelineIdList']
r['result'] = pipelines
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
r['error'] = six.text_type(e)
return r | [
"def",
"list_pipelines",
"(",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"client",
"=",
"_get_client",
"(",
"region",
",",
"key",
",",
"keyid",
",",
"profile",
")",
"r",
"=",
"{... | Get a list of pipeline ids and names for all pipelines.
CLI Example:
.. code-block:: bash
salt myminion boto_datapipeline.list_pipelines profile=myprofile | [
"Get",
"a",
"list",
"of",
"pipeline",
"ids",
"and",
"names",
"for",
"all",
"pipelines",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_datapipeline.py#L144-L164 | train |
saltstack/salt | salt/modules/boto_datapipeline.py | pipeline_id_from_name | def pipeline_id_from_name(name, region=None, key=None, keyid=None, profile=None):
'''
Get the pipeline id, if it exists, for the given name.
CLI example:
.. code-block:: bash
salt myminion boto_datapipeline.pipeline_id_from_name my_pipeline_name
'''
r = {}
result_pipelines = list_pipelines()
if 'error' in result_pipelines:
return result_pipelines
for pipeline in result_pipelines['result']:
if pipeline['name'] == name:
r['result'] = pipeline['id']
return r
r['error'] = 'No pipeline found with name={0}'.format(name)
return r | python | def pipeline_id_from_name(name, region=None, key=None, keyid=None, profile=None):
'''
Get the pipeline id, if it exists, for the given name.
CLI example:
.. code-block:: bash
salt myminion boto_datapipeline.pipeline_id_from_name my_pipeline_name
'''
r = {}
result_pipelines = list_pipelines()
if 'error' in result_pipelines:
return result_pipelines
for pipeline in result_pipelines['result']:
if pipeline['name'] == name:
r['result'] = pipeline['id']
return r
r['error'] = 'No pipeline found with name={0}'.format(name)
return r | [
"def",
"pipeline_id_from_name",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"r",
"=",
"{",
"}",
"result_pipelines",
"=",
"list_pipelines",
"(",
")",
"if",
"'error'"... | Get the pipeline id, if it exists, for the given name.
CLI example:
.. code-block:: bash
salt myminion boto_datapipeline.pipeline_id_from_name my_pipeline_name | [
"Get",
"the",
"pipeline",
"id",
"if",
"it",
"exists",
"for",
"the",
"given",
"name",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_datapipeline.py#L167-L187 | train |
saltstack/salt | salt/modules/boto_datapipeline.py | put_pipeline_definition | def put_pipeline_definition(pipeline_id, pipeline_objects, parameter_objects=None,
parameter_values=None, region=None, key=None, keyid=None, profile=None):
'''
Add tasks, schedules, and preconditions to the specified pipeline. This function is
idempotent and will replace an existing definition.
CLI example:
.. code-block:: bash
salt myminion boto_datapipeline.put_pipeline_definition my_pipeline_id my_pipeline_objects
'''
parameter_objects = parameter_objects or []
parameter_values = parameter_values or []
client = _get_client(region, key, keyid, profile)
r = {}
try:
response = client.put_pipeline_definition(
pipelineId=pipeline_id,
pipelineObjects=pipeline_objects,
parameterObjects=parameter_objects,
parameterValues=parameter_values,
)
if response['errored']:
r['error'] = response['validationErrors']
else:
r['result'] = response
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
r['error'] = six.text_type(e)
return r | python | def put_pipeline_definition(pipeline_id, pipeline_objects, parameter_objects=None,
parameter_values=None, region=None, key=None, keyid=None, profile=None):
'''
Add tasks, schedules, and preconditions to the specified pipeline. This function is
idempotent and will replace an existing definition.
CLI example:
.. code-block:: bash
salt myminion boto_datapipeline.put_pipeline_definition my_pipeline_id my_pipeline_objects
'''
parameter_objects = parameter_objects or []
parameter_values = parameter_values or []
client = _get_client(region, key, keyid, profile)
r = {}
try:
response = client.put_pipeline_definition(
pipelineId=pipeline_id,
pipelineObjects=pipeline_objects,
parameterObjects=parameter_objects,
parameterValues=parameter_values,
)
if response['errored']:
r['error'] = response['validationErrors']
else:
r['result'] = response
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
r['error'] = six.text_type(e)
return r | [
"def",
"put_pipeline_definition",
"(",
"pipeline_id",
",",
"pipeline_objects",
",",
"parameter_objects",
"=",
"None",
",",
"parameter_values",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"... | Add tasks, schedules, and preconditions to the specified pipeline. This function is
idempotent and will replace an existing definition.
CLI example:
.. code-block:: bash
salt myminion boto_datapipeline.put_pipeline_definition my_pipeline_id my_pipeline_objects | [
"Add",
"tasks",
"schedules",
"and",
"preconditions",
"to",
"the",
"specified",
"pipeline",
".",
"This",
"function",
"is",
"idempotent",
"and",
"will",
"replace",
"an",
"existing",
"definition",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_datapipeline.py#L190-L219 | train |
saltstack/salt | salt/modules/boto_datapipeline.py | _get_client | def _get_client(region, key, keyid, profile):
'''
Get a boto connection to Data Pipeline.
'''
session = _get_session(region, key, keyid, profile)
if not session:
log.error("Failed to get datapipeline client.")
return None
return session.client('datapipeline') | python | def _get_client(region, key, keyid, profile):
'''
Get a boto connection to Data Pipeline.
'''
session = _get_session(region, key, keyid, profile)
if not session:
log.error("Failed to get datapipeline client.")
return None
return session.client('datapipeline') | [
"def",
"_get_client",
"(",
"region",
",",
"key",
",",
"keyid",
",",
"profile",
")",
":",
"session",
"=",
"_get_session",
"(",
"region",
",",
"key",
",",
"keyid",
",",
"profile",
")",
"if",
"not",
"session",
":",
"log",
".",
"error",
"(",
"\"Failed to g... | Get a boto connection to Data Pipeline. | [
"Get",
"a",
"boto",
"connection",
"to",
"Data",
"Pipeline",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_datapipeline.py#L222-L231 | train |
saltstack/salt | salt/modules/boto_datapipeline.py | _get_session | def _get_session(region, key, keyid, profile):
'''
Get a boto3 session
'''
if profile:
if isinstance(profile, six.string_types):
_profile = __salt__['config.option'](profile)
elif isinstance(profile, dict):
_profile = profile
key = _profile.get('key', None)
keyid = _profile.get('keyid', None)
region = _profile.get('region', None)
if not region and __salt__['config.option']('datapipeline.region'):
region = __salt__['config.option']('datapipeline.region')
if not region:
region = 'us-east-1'
return boto3.session.Session(
region_name=region,
aws_secret_access_key=key,
aws_access_key_id=keyid,
) | python | def _get_session(region, key, keyid, profile):
'''
Get a boto3 session
'''
if profile:
if isinstance(profile, six.string_types):
_profile = __salt__['config.option'](profile)
elif isinstance(profile, dict):
_profile = profile
key = _profile.get('key', None)
keyid = _profile.get('keyid', None)
region = _profile.get('region', None)
if not region and __salt__['config.option']('datapipeline.region'):
region = __salt__['config.option']('datapipeline.region')
if not region:
region = 'us-east-1'
return boto3.session.Session(
region_name=region,
aws_secret_access_key=key,
aws_access_key_id=keyid,
) | [
"def",
"_get_session",
"(",
"region",
",",
"key",
",",
"keyid",
",",
"profile",
")",
":",
"if",
"profile",
":",
"if",
"isinstance",
"(",
"profile",
",",
"six",
".",
"string_types",
")",
":",
"_profile",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
... | Get a boto3 session | [
"Get",
"a",
"boto3",
"session"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_datapipeline.py#L234-L257 | train |
saltstack/salt | salt/modules/qemu_img.py | make_image | def make_image(location, size, fmt):
'''
Create a blank virtual machine image file of the specified size in
megabytes. The image can be created in any format supported by qemu
CLI Example:
.. code-block:: bash
salt '*' qemu_img.make_image /tmp/image.qcow 2048 qcow2
salt '*' qemu_img.make_image /tmp/image.raw 10240 raw
'''
if not os.path.isabs(location):
return ''
if not os.path.isdir(os.path.dirname(location)):
return ''
if not __salt__['cmd.retcode'](
'qemu-img create -f {0} {1} {2}M'.format(
fmt,
location,
size),
python_shell=False):
return location
return '' | python | def make_image(location, size, fmt):
'''
Create a blank virtual machine image file of the specified size in
megabytes. The image can be created in any format supported by qemu
CLI Example:
.. code-block:: bash
salt '*' qemu_img.make_image /tmp/image.qcow 2048 qcow2
salt '*' qemu_img.make_image /tmp/image.raw 10240 raw
'''
if not os.path.isabs(location):
return ''
if not os.path.isdir(os.path.dirname(location)):
return ''
if not __salt__['cmd.retcode'](
'qemu-img create -f {0} {1} {2}M'.format(
fmt,
location,
size),
python_shell=False):
return location
return '' | [
"def",
"make_image",
"(",
"location",
",",
"size",
",",
"fmt",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"location",
")",
":",
"return",
"''",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"dirname"... | Create a blank virtual machine image file of the specified size in
megabytes. The image can be created in any format supported by qemu
CLI Example:
.. code-block:: bash
salt '*' qemu_img.make_image /tmp/image.qcow 2048 qcow2
salt '*' qemu_img.make_image /tmp/image.raw 10240 raw | [
"Create",
"a",
"blank",
"virtual",
"machine",
"image",
"file",
"of",
"the",
"specified",
"size",
"in",
"megabytes",
".",
"The",
"image",
"can",
"be",
"created",
"in",
"any",
"format",
"supported",
"by",
"qemu"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/qemu_img.py#L28-L51 | train |
saltstack/salt | salt/modules/qemu_img.py | convert | def convert(orig, dest, fmt):
'''
Convert an existing disk image to another format using qemu-img
CLI Example:
.. code-block:: bash
salt '*' qemu_img.convert /path/to/original.img /path/to/new.img qcow2
'''
cmd = ('qemu-img', 'convert', '-O', fmt, orig, dest)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] == 0:
return True
else:
return ret['stderr'] | python | def convert(orig, dest, fmt):
'''
Convert an existing disk image to another format using qemu-img
CLI Example:
.. code-block:: bash
salt '*' qemu_img.convert /path/to/original.img /path/to/new.img qcow2
'''
cmd = ('qemu-img', 'convert', '-O', fmt, orig, dest)
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] == 0:
return True
else:
return ret['stderr'] | [
"def",
"convert",
"(",
"orig",
",",
"dest",
",",
"fmt",
")",
":",
"cmd",
"=",
"(",
"'qemu-img'",
",",
"'convert'",
",",
"'-O'",
",",
"fmt",
",",
"orig",
",",
"dest",
")",
"ret",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
",",
"python_s... | Convert an existing disk image to another format using qemu-img
CLI Example:
.. code-block:: bash
salt '*' qemu_img.convert /path/to/original.img /path/to/new.img qcow2 | [
"Convert",
"an",
"existing",
"disk",
"image",
"to",
"another",
"format",
"using",
"qemu",
"-",
"img"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/qemu_img.py#L54-L69 | train |
saltstack/salt | salt/modules/win_network.py | ping | def ping(host, timeout=False, return_boolean=False):
'''
Performs a ping to a host
CLI Example:
.. code-block:: bash
salt '*' network.ping archlinux.org
.. versionadded:: 2016.11.0
Return a True or False instead of ping output.
.. code-block:: bash
salt '*' network.ping archlinux.org return_boolean=True
Set the time to wait for a response in seconds.
.. code-block:: bash
salt '*' network.ping archlinux.org timeout=3
'''
if timeout:
# Windows ping differs by having timeout be for individual echo requests.'
# Divide timeout by tries to mimic BSD behaviour.
timeout = int(timeout) * 1000 // 4
cmd = ['ping', '-n', '4', '-w', six.text_type(timeout), salt.utils.network.sanitize_host(host)]
else:
cmd = ['ping', '-n', '4', salt.utils.network.sanitize_host(host)]
if return_boolean:
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
else:
return __salt__['cmd.run'](cmd, python_shell=False) | python | def ping(host, timeout=False, return_boolean=False):
'''
Performs a ping to a host
CLI Example:
.. code-block:: bash
salt '*' network.ping archlinux.org
.. versionadded:: 2016.11.0
Return a True or False instead of ping output.
.. code-block:: bash
salt '*' network.ping archlinux.org return_boolean=True
Set the time to wait for a response in seconds.
.. code-block:: bash
salt '*' network.ping archlinux.org timeout=3
'''
if timeout:
# Windows ping differs by having timeout be for individual echo requests.'
# Divide timeout by tries to mimic BSD behaviour.
timeout = int(timeout) * 1000 // 4
cmd = ['ping', '-n', '4', '-w', six.text_type(timeout), salt.utils.network.sanitize_host(host)]
else:
cmd = ['ping', '-n', '4', salt.utils.network.sanitize_host(host)]
if return_boolean:
ret = __salt__['cmd.run_all'](cmd, python_shell=False)
if ret['retcode'] != 0:
return False
else:
return True
else:
return __salt__['cmd.run'](cmd, python_shell=False) | [
"def",
"ping",
"(",
"host",
",",
"timeout",
"=",
"False",
",",
"return_boolean",
"=",
"False",
")",
":",
"if",
"timeout",
":",
"# Windows ping differs by having timeout be for individual echo requests.'",
"# Divide timeout by tries to mimic BSD behaviour.",
"timeout",
"=",
... | Performs a ping to a host
CLI Example:
.. code-block:: bash
salt '*' network.ping archlinux.org
.. versionadded:: 2016.11.0
Return a True or False instead of ping output.
.. code-block:: bash
salt '*' network.ping archlinux.org return_boolean=True
Set the time to wait for a response in seconds.
.. code-block:: bash
salt '*' network.ping archlinux.org timeout=3 | [
"Performs",
"a",
"ping",
"to",
"a",
"host"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_network.py#L69-L107 | train |
saltstack/salt | salt/modules/win_network.py | netstat | def netstat():
'''
Return information on open ports and states
CLI Example:
.. code-block:: bash
salt '*' network.netstat
'''
ret = []
cmd = ['netstat', '-nao']
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if line.startswith(' TCP'):
ret.append({
'local-address': comps[1],
'proto': comps[0],
'remote-address': comps[2],
'state': comps[3],
'program': comps[4]})
if line.startswith(' UDP'):
ret.append({
'local-address': comps[1],
'proto': comps[0],
'remote-address': comps[2],
'state': None,
'program': comps[3]})
return ret | python | def netstat():
'''
Return information on open ports and states
CLI Example:
.. code-block:: bash
salt '*' network.netstat
'''
ret = []
cmd = ['netstat', '-nao']
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
comps = line.split()
if line.startswith(' TCP'):
ret.append({
'local-address': comps[1],
'proto': comps[0],
'remote-address': comps[2],
'state': comps[3],
'program': comps[4]})
if line.startswith(' UDP'):
ret.append({
'local-address': comps[1],
'proto': comps[0],
'remote-address': comps[2],
'state': None,
'program': comps[3]})
return ret | [
"def",
"netstat",
"(",
")",
":",
"ret",
"=",
"[",
"]",
"cmd",
"=",
"[",
"'netstat'",
",",
"'-nao'",
"]",
"lines",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")",
".",
"splitlines",
"(",
")",
"for",
"line"... | Return information on open ports and states
CLI Example:
.. code-block:: bash
salt '*' network.netstat | [
"Return",
"information",
"on",
"open",
"ports",
"and",
"states"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_network.py#L110-L139 | train |
saltstack/salt | salt/modules/win_network.py | traceroute | def traceroute(host):
'''
Performs a traceroute to a 3rd party host
CLI Example:
.. code-block:: bash
salt '*' network.traceroute archlinux.org
'''
ret = []
cmd = ['tracert', salt.utils.network.sanitize_host(host)]
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
if ' ' not in line:
continue
if line.startswith('Trac'):
continue
if line.startswith('over'):
continue
comps = line.split()
complength = len(comps)
# This method still needs to better catch rows of other lengths
# For example if some of the ms returns are '*'
if complength == 9:
result = {
'count': comps[0],
'hostname': comps[7],
'ip': comps[8],
'ms1': comps[1],
'ms2': comps[3],
'ms3': comps[5]}
ret.append(result)
elif complength == 8:
result = {
'count': comps[0],
'hostname': None,
'ip': comps[7],
'ms1': comps[1],
'ms2': comps[3],
'ms3': comps[5]}
ret.append(result)
else:
result = {
'count': comps[0],
'hostname': None,
'ip': None,
'ms1': None,
'ms2': None,
'ms3': None}
ret.append(result)
return ret | python | def traceroute(host):
'''
Performs a traceroute to a 3rd party host
CLI Example:
.. code-block:: bash
salt '*' network.traceroute archlinux.org
'''
ret = []
cmd = ['tracert', salt.utils.network.sanitize_host(host)]
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
if ' ' not in line:
continue
if line.startswith('Trac'):
continue
if line.startswith('over'):
continue
comps = line.split()
complength = len(comps)
# This method still needs to better catch rows of other lengths
# For example if some of the ms returns are '*'
if complength == 9:
result = {
'count': comps[0],
'hostname': comps[7],
'ip': comps[8],
'ms1': comps[1],
'ms2': comps[3],
'ms3': comps[5]}
ret.append(result)
elif complength == 8:
result = {
'count': comps[0],
'hostname': None,
'ip': comps[7],
'ms1': comps[1],
'ms2': comps[3],
'ms3': comps[5]}
ret.append(result)
else:
result = {
'count': comps[0],
'hostname': None,
'ip': None,
'ms1': None,
'ms2': None,
'ms3': None}
ret.append(result)
return ret | [
"def",
"traceroute",
"(",
"host",
")",
":",
"ret",
"=",
"[",
"]",
"cmd",
"=",
"[",
"'tracert'",
",",
"salt",
".",
"utils",
".",
"network",
".",
"sanitize_host",
"(",
"host",
")",
"]",
"lines",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
","... | Performs a traceroute to a 3rd party host
CLI Example:
.. code-block:: bash
salt '*' network.traceroute archlinux.org | [
"Performs",
"a",
"traceroute",
"to",
"a",
"3rd",
"party",
"host"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_network.py#L142-L193 | train |
saltstack/salt | salt/modules/win_network.py | nslookup | def nslookup(host):
'''
Query DNS for information about a domain or ip address
CLI Example:
.. code-block:: bash
salt '*' network.nslookup archlinux.org
'''
ret = []
addresses = []
cmd = ['nslookup', salt.utils.network.sanitize_host(host)]
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
if addresses:
# We're in the last block listing addresses
addresses.append(line.strip())
continue
if line.startswith('Non-authoritative'):
continue
if 'Addresses' in line:
comps = line.split(":", 1)
addresses.append(comps[1].strip())
continue
if ":" in line:
comps = line.split(":", 1)
ret.append({comps[0].strip(): comps[1].strip()})
if addresses:
ret.append({'Addresses': addresses})
return ret | python | def nslookup(host):
'''
Query DNS for information about a domain or ip address
CLI Example:
.. code-block:: bash
salt '*' network.nslookup archlinux.org
'''
ret = []
addresses = []
cmd = ['nslookup', salt.utils.network.sanitize_host(host)]
lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in lines:
if addresses:
# We're in the last block listing addresses
addresses.append(line.strip())
continue
if line.startswith('Non-authoritative'):
continue
if 'Addresses' in line:
comps = line.split(":", 1)
addresses.append(comps[1].strip())
continue
if ":" in line:
comps = line.split(":", 1)
ret.append({comps[0].strip(): comps[1].strip()})
if addresses:
ret.append({'Addresses': addresses})
return ret | [
"def",
"nslookup",
"(",
"host",
")",
":",
"ret",
"=",
"[",
"]",
"addresses",
"=",
"[",
"]",
"cmd",
"=",
"[",
"'nslookup'",
",",
"salt",
".",
"utils",
".",
"network",
".",
"sanitize_host",
"(",
"host",
")",
"]",
"lines",
"=",
"__salt__",
"[",
"'cmd.... | Query DNS for information about a domain or ip address
CLI Example:
.. code-block:: bash
salt '*' network.nslookup archlinux.org | [
"Query",
"DNS",
"for",
"information",
"about",
"a",
"domain",
"or",
"ip",
"address"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_network.py#L196-L226 | train |
saltstack/salt | salt/modules/win_network.py | get_route | def get_route(ip):
'''
Return routing information for given destination ip
.. versionadded:: 2016.11.5
CLI Example::
salt '*' network.get_route 10.10.10.10
'''
cmd = 'Find-NetRoute -RemoteIPAddress {0}'.format(ip)
out = __salt__['cmd.run'](cmd, shell='powershell', python_shell=True)
regexp = re.compile(
r"^IPAddress\s+:\s(?P<source>[\d\.:]+)?.*"
r"^InterfaceAlias\s+:\s(?P<interface>[\w\.\:\-\ ]+)?.*"
r"^NextHop\s+:\s(?P<gateway>[\d\.:]+)",
flags=re.MULTILINE | re.DOTALL
)
m = regexp.search(out)
ret = {
'destination': ip,
'gateway': m.group('gateway'),
'interface': m.group('interface'),
'source': m.group('source')
}
return ret | python | def get_route(ip):
'''
Return routing information for given destination ip
.. versionadded:: 2016.11.5
CLI Example::
salt '*' network.get_route 10.10.10.10
'''
cmd = 'Find-NetRoute -RemoteIPAddress {0}'.format(ip)
out = __salt__['cmd.run'](cmd, shell='powershell', python_shell=True)
regexp = re.compile(
r"^IPAddress\s+:\s(?P<source>[\d\.:]+)?.*"
r"^InterfaceAlias\s+:\s(?P<interface>[\w\.\:\-\ ]+)?.*"
r"^NextHop\s+:\s(?P<gateway>[\d\.:]+)",
flags=re.MULTILINE | re.DOTALL
)
m = regexp.search(out)
ret = {
'destination': ip,
'gateway': m.group('gateway'),
'interface': m.group('interface'),
'source': m.group('source')
}
return ret | [
"def",
"get_route",
"(",
"ip",
")",
":",
"cmd",
"=",
"'Find-NetRoute -RemoteIPAddress {0}'",
".",
"format",
"(",
"ip",
")",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
",",
"shell",
"=",
"'powershell'",
",",
"python_shell",
"=",
"True",
")",... | Return routing information for given destination ip
.. versionadded:: 2016.11.5
CLI Example::
salt '*' network.get_route 10.10.10.10 | [
"Return",
"routing",
"information",
"for",
"given",
"destination",
"ip"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_network.py#L229-L255 | train |
saltstack/salt | salt/modules/win_network.py | dig | def dig(host):
'''
Performs a DNS lookup with dig
Note: dig must be installed on the Windows minion
CLI Example:
.. code-block:: bash
salt '*' network.dig archlinux.org
'''
cmd = ['dig', salt.utils.network.sanitize_host(host)]
return __salt__['cmd.run'](cmd, python_shell=False) | python | def dig(host):
'''
Performs a DNS lookup with dig
Note: dig must be installed on the Windows minion
CLI Example:
.. code-block:: bash
salt '*' network.dig archlinux.org
'''
cmd = ['dig', salt.utils.network.sanitize_host(host)]
return __salt__['cmd.run'](cmd, python_shell=False) | [
"def",
"dig",
"(",
"host",
")",
":",
"cmd",
"=",
"[",
"'dig'",
",",
"salt",
".",
"utils",
".",
"network",
".",
"sanitize_host",
"(",
"host",
")",
"]",
"return",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
",",
"python_shell",
"=",
"False",
")"
] | Performs a DNS lookup with dig
Note: dig must be installed on the Windows minion
CLI Example:
.. code-block:: bash
salt '*' network.dig archlinux.org | [
"Performs",
"a",
"DNS",
"lookup",
"with",
"dig"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_network.py#L258-L271 | train |
saltstack/salt | salt/modules/win_network.py | interfaces_names | def interfaces_names():
'''
Return a list of all the interfaces names
CLI Example:
.. code-block:: bash
salt '*' network.interfaces_names
'''
ret = []
with salt.utils.winapi.Com():
c = wmi.WMI()
for iface in c.Win32_NetworkAdapter(NetEnabled=True):
ret.append(iface.NetConnectionID)
return ret | python | def interfaces_names():
'''
Return a list of all the interfaces names
CLI Example:
.. code-block:: bash
salt '*' network.interfaces_names
'''
ret = []
with salt.utils.winapi.Com():
c = wmi.WMI()
for iface in c.Win32_NetworkAdapter(NetEnabled=True):
ret.append(iface.NetConnectionID)
return ret | [
"def",
"interfaces_names",
"(",
")",
":",
"ret",
"=",
"[",
"]",
"with",
"salt",
".",
"utils",
".",
"winapi",
".",
"Com",
"(",
")",
":",
"c",
"=",
"wmi",
".",
"WMI",
"(",
")",
"for",
"iface",
"in",
"c",
".",
"Win32_NetworkAdapter",
"(",
"NetEnabled"... | Return a list of all the interfaces names
CLI Example:
.. code-block:: bash
salt '*' network.interfaces_names | [
"Return",
"a",
"list",
"of",
"all",
"the",
"interfaces",
"names"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_network.py#L274-L290 | train |
saltstack/salt | salt/modules/win_network.py | ip_addrs | def ip_addrs(interface=None, include_loopback=False, cidr=None, type=None):
'''
Returns a list of IPv4 addresses assigned to the host.
interface
Only IP addresses from that interface will be returned.
include_loopback : False
Include loopback 127.0.0.1 IPv4 address.
cidr
Describes subnet using CIDR notation and only IPv4 addresses that belong
to this subnet will be returned.
.. versionchanged:: 2019.2.0
type
If option set to 'public' then only public addresses will be returned.
Ditto for 'private'.
.. versionchanged:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' network.ip_addrs
salt '*' network.ip_addrs cidr=10.0.0.0/8
salt '*' network.ip_addrs cidr=192.168.0.0/16 type=private
'''
addrs = salt.utils.network.ip_addrs(interface=interface,
include_loopback=include_loopback)
if cidr:
return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])]
else:
if type == 'public':
return [i for i in addrs if not is_private(i)]
elif type == 'private':
return [i for i in addrs if is_private(i)]
else:
return addrs | python | def ip_addrs(interface=None, include_loopback=False, cidr=None, type=None):
'''
Returns a list of IPv4 addresses assigned to the host.
interface
Only IP addresses from that interface will be returned.
include_loopback : False
Include loopback 127.0.0.1 IPv4 address.
cidr
Describes subnet using CIDR notation and only IPv4 addresses that belong
to this subnet will be returned.
.. versionchanged:: 2019.2.0
type
If option set to 'public' then only public addresses will be returned.
Ditto for 'private'.
.. versionchanged:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' network.ip_addrs
salt '*' network.ip_addrs cidr=10.0.0.0/8
salt '*' network.ip_addrs cidr=192.168.0.0/16 type=private
'''
addrs = salt.utils.network.ip_addrs(interface=interface,
include_loopback=include_loopback)
if cidr:
return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])]
else:
if type == 'public':
return [i for i in addrs if not is_private(i)]
elif type == 'private':
return [i for i in addrs if is_private(i)]
else:
return addrs | [
"def",
"ip_addrs",
"(",
"interface",
"=",
"None",
",",
"include_loopback",
"=",
"False",
",",
"cidr",
"=",
"None",
",",
"type",
"=",
"None",
")",
":",
"addrs",
"=",
"salt",
".",
"utils",
".",
"network",
".",
"ip_addrs",
"(",
"interface",
"=",
"interfac... | Returns a list of IPv4 addresses assigned to the host.
interface
Only IP addresses from that interface will be returned.
include_loopback : False
Include loopback 127.0.0.1 IPv4 address.
cidr
Describes subnet using CIDR notation and only IPv4 addresses that belong
to this subnet will be returned.
.. versionchanged:: 2019.2.0
type
If option set to 'public' then only public addresses will be returned.
Ditto for 'private'.
.. versionchanged:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' network.ip_addrs
salt '*' network.ip_addrs cidr=10.0.0.0/8
salt '*' network.ip_addrs cidr=192.168.0.0/16 type=private | [
"Returns",
"a",
"list",
"of",
"IPv4",
"addresses",
"assigned",
"to",
"the",
"host",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_network.py#L349-L389 | train |
saltstack/salt | salt/modules/win_network.py | ip_addrs6 | def ip_addrs6(interface=None, include_loopback=False, cidr=None):
'''
Returns a list of IPv6 addresses assigned to the host.
interface
Only IP addresses from that interface will be returned.
include_loopback : False
Include loopback ::1 IPv6 address.
cidr
Describes subnet using CIDR notation and only IPv6 addresses that belong
to this subnet will be returned.
.. versionchanged:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' network.ip_addrs6
salt '*' network.ip_addrs6 cidr=2000::/3
'''
addrs = salt.utils.network.ip_addrs6(interface=interface,
include_loopback=include_loopback)
if cidr:
return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])]
else:
return addrs | python | def ip_addrs6(interface=None, include_loopback=False, cidr=None):
'''
Returns a list of IPv6 addresses assigned to the host.
interface
Only IP addresses from that interface will be returned.
include_loopback : False
Include loopback ::1 IPv6 address.
cidr
Describes subnet using CIDR notation and only IPv6 addresses that belong
to this subnet will be returned.
.. versionchanged:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' network.ip_addrs6
salt '*' network.ip_addrs6 cidr=2000::/3
'''
addrs = salt.utils.network.ip_addrs6(interface=interface,
include_loopback=include_loopback)
if cidr:
return [i for i in addrs if salt.utils.network.in_subnet(cidr, [i])]
else:
return addrs | [
"def",
"ip_addrs6",
"(",
"interface",
"=",
"None",
",",
"include_loopback",
"=",
"False",
",",
"cidr",
"=",
"None",
")",
":",
"addrs",
"=",
"salt",
".",
"utils",
".",
"network",
".",
"ip_addrs6",
"(",
"interface",
"=",
"interface",
",",
"include_loopback",... | Returns a list of IPv6 addresses assigned to the host.
interface
Only IP addresses from that interface will be returned.
include_loopback : False
Include loopback ::1 IPv6 address.
cidr
Describes subnet using CIDR notation and only IPv6 addresses that belong
to this subnet will be returned.
.. versionchanged:: 2019.2.0
CLI Example:
.. code-block:: bash
salt '*' network.ip_addrs6
salt '*' network.ip_addrs6 cidr=2000::/3 | [
"Returns",
"a",
"list",
"of",
"IPv6",
"addresses",
"assigned",
"to",
"the",
"host",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_network.py#L395-L423 | train |
saltstack/salt | salt/modules/win_network.py | connect | def connect(host, port=None, **kwargs):
'''
Test connectivity to a host using a particular
port from the minion.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' network.connect archlinux.org 80
salt '*' network.connect archlinux.org 80 timeout=3
salt '*' network.connect archlinux.org 80 timeout=3 family=ipv4
salt '*' network.connect google-public-dns-a.google.com port=53 proto=udp timeout=3
'''
ret = {'result': None,
'comment': ''}
if not host:
ret['result'] = False
ret['comment'] = 'Required argument, host, is missing.'
return ret
if not port:
ret['result'] = False
ret['comment'] = 'Required argument, port, is missing.'
return ret
proto = kwargs.get('proto', 'tcp')
timeout = kwargs.get('timeout', 5)
family = kwargs.get('family', None)
if salt.utils.validate.net.ipv4_addr(host) or salt.utils.validate.net.ipv6_addr(host):
address = host
else:
address = '{0}'.format(salt.utils.network.sanitize_host(host))
try:
if proto == 'udp':
__proto = socket.SOL_UDP
else:
__proto = socket.SOL_TCP
proto = 'tcp'
if family:
if family == 'ipv4':
__family = socket.AF_INET
elif family == 'ipv6':
__family = socket.AF_INET6
else:
__family = 0
else:
__family = 0
(family,
socktype,
_proto,
garbage,
_address) = socket.getaddrinfo(address, port, __family, 0, __proto)[0]
skt = socket.socket(family, socktype, _proto)
skt.settimeout(timeout)
if proto == 'udp':
# Generate a random string of a
# decent size to test UDP connection
md5h = hashlib.md5()
md5h.update(datetime.datetime.now().strftime('%s'))
msg = md5h.hexdigest()
skt.sendto(msg, _address)
recv, svr = skt.recvfrom(255)
skt.close()
else:
skt.connect(_address)
skt.shutdown(2)
except Exception as exc:
ret['result'] = False
ret['comment'] = 'Unable to connect to {0} ({1}) on {2} port {3}'\
.format(host, _address[0], proto, port)
return ret
ret['result'] = True
ret['comment'] = 'Successfully connected to {0} ({1}) on {2} port {3}'\
.format(host, _address[0], proto, port)
return ret | python | def connect(host, port=None, **kwargs):
'''
Test connectivity to a host using a particular
port from the minion.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' network.connect archlinux.org 80
salt '*' network.connect archlinux.org 80 timeout=3
salt '*' network.connect archlinux.org 80 timeout=3 family=ipv4
salt '*' network.connect google-public-dns-a.google.com port=53 proto=udp timeout=3
'''
ret = {'result': None,
'comment': ''}
if not host:
ret['result'] = False
ret['comment'] = 'Required argument, host, is missing.'
return ret
if not port:
ret['result'] = False
ret['comment'] = 'Required argument, port, is missing.'
return ret
proto = kwargs.get('proto', 'tcp')
timeout = kwargs.get('timeout', 5)
family = kwargs.get('family', None)
if salt.utils.validate.net.ipv4_addr(host) or salt.utils.validate.net.ipv6_addr(host):
address = host
else:
address = '{0}'.format(salt.utils.network.sanitize_host(host))
try:
if proto == 'udp':
__proto = socket.SOL_UDP
else:
__proto = socket.SOL_TCP
proto = 'tcp'
if family:
if family == 'ipv4':
__family = socket.AF_INET
elif family == 'ipv6':
__family = socket.AF_INET6
else:
__family = 0
else:
__family = 0
(family,
socktype,
_proto,
garbage,
_address) = socket.getaddrinfo(address, port, __family, 0, __proto)[0]
skt = socket.socket(family, socktype, _proto)
skt.settimeout(timeout)
if proto == 'udp':
# Generate a random string of a
# decent size to test UDP connection
md5h = hashlib.md5()
md5h.update(datetime.datetime.now().strftime('%s'))
msg = md5h.hexdigest()
skt.sendto(msg, _address)
recv, svr = skt.recvfrom(255)
skt.close()
else:
skt.connect(_address)
skt.shutdown(2)
except Exception as exc:
ret['result'] = False
ret['comment'] = 'Unable to connect to {0} ({1}) on {2} port {3}'\
.format(host, _address[0], proto, port)
return ret
ret['result'] = True
ret['comment'] = 'Successfully connected to {0} ({1}) on {2} port {3}'\
.format(host, _address[0], proto, port)
return ret | [
"def",
"connect",
"(",
"host",
",",
"port",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
"}",
"if",
"not",
"host",
":",
"ret",
"[",
"'result'",
"]",
"=",
"False",
"ret",
... | Test connectivity to a host using a particular
port from the minion.
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' network.connect archlinux.org 80
salt '*' network.connect archlinux.org 80 timeout=3
salt '*' network.connect archlinux.org 80 timeout=3 family=ipv4
salt '*' network.connect google-public-dns-a.google.com port=53 proto=udp timeout=3 | [
"Test",
"connectivity",
"to",
"a",
"host",
"using",
"a",
"particular",
"port",
"from",
"the",
"minion",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_network.py#L429-L518 | train |
saltstack/salt | salt/returners/pushover_returner.py | _post_message | def _post_message(user,
device,
message,
title,
priority,
expire,
retry,
sound,
api_version=1,
token=None):
'''
Send a message to a Pushover user or group.
:param user: The user or group to send to, must be key of user or group not email address.
:param message: The message to send to the PushOver user or group.
:param title: Specify who the message is from.
:param priority The priority of the message, defaults to 0.
:param api_version: The PushOver API version, if not specified in the configuration.
:param notify: Whether to notify the room, default: False.
:param token: The PushOver token, if not specified in the configuration.
:return: Boolean if message was sent successfully.
'''
user_validate = salt.utils.pushover.validate_user(user, device, token)
if not user_validate['result']:
return user_validate
parameters = dict()
parameters['user'] = user
parameters['device'] = device
parameters['token'] = token
parameters['title'] = title
parameters['priority'] = priority
parameters['expire'] = expire
parameters['retry'] = retry
parameters['message'] = message
if sound:
sound_validate = salt.utils.pushover.validate_sound(sound, token)
if sound_validate['res']:
parameters['sound'] = sound
result = salt.utils.pushover.query(function='message',
method='POST',
header_dict={'Content-Type': 'application/x-www-form-urlencoded'},
data=_urlencode(parameters),
opts=__opts__)
return result | python | def _post_message(user,
device,
message,
title,
priority,
expire,
retry,
sound,
api_version=1,
token=None):
'''
Send a message to a Pushover user or group.
:param user: The user or group to send to, must be key of user or group not email address.
:param message: The message to send to the PushOver user or group.
:param title: Specify who the message is from.
:param priority The priority of the message, defaults to 0.
:param api_version: The PushOver API version, if not specified in the configuration.
:param notify: Whether to notify the room, default: False.
:param token: The PushOver token, if not specified in the configuration.
:return: Boolean if message was sent successfully.
'''
user_validate = salt.utils.pushover.validate_user(user, device, token)
if not user_validate['result']:
return user_validate
parameters = dict()
parameters['user'] = user
parameters['device'] = device
parameters['token'] = token
parameters['title'] = title
parameters['priority'] = priority
parameters['expire'] = expire
parameters['retry'] = retry
parameters['message'] = message
if sound:
sound_validate = salt.utils.pushover.validate_sound(sound, token)
if sound_validate['res']:
parameters['sound'] = sound
result = salt.utils.pushover.query(function='message',
method='POST',
header_dict={'Content-Type': 'application/x-www-form-urlencoded'},
data=_urlencode(parameters),
opts=__opts__)
return result | [
"def",
"_post_message",
"(",
"user",
",",
"device",
",",
"message",
",",
"title",
",",
"priority",
",",
"expire",
",",
"retry",
",",
"sound",
",",
"api_version",
"=",
"1",
",",
"token",
"=",
"None",
")",
":",
"user_validate",
"=",
"salt",
".",
"utils",... | Send a message to a Pushover user or group.
:param user: The user or group to send to, must be key of user or group not email address.
:param message: The message to send to the PushOver user or group.
:param title: Specify who the message is from.
:param priority The priority of the message, defaults to 0.
:param api_version: The PushOver API version, if not specified in the configuration.
:param notify: Whether to notify the room, default: False.
:param token: The PushOver token, if not specified in the configuration.
:return: Boolean if message was sent successfully. | [
"Send",
"a",
"message",
"to",
"a",
"Pushover",
"user",
"or",
"group",
".",
":",
"param",
"user",
":",
"The",
"user",
"or",
"group",
"to",
"send",
"to",
"must",
"be",
"key",
"of",
"user",
"or",
"group",
"not",
"email",
"address",
".",
":",
"param",
... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/pushover_returner.py#L151-L198 | train |
saltstack/salt | salt/returners/pushover_returner.py | returner | def returner(ret):
'''
Send an PushOver message with the data
'''
_options = _get_options(ret)
user = _options.get('user')
device = _options.get('device')
token = _options.get('token')
title = _options.get('title')
priority = _options.get('priority')
expire = _options.get('expire')
retry = _options.get('retry')
sound = _options.get('sound')
if not token:
raise SaltInvocationError('Pushover token is unavailable.')
if not user:
raise SaltInvocationError('Pushover user key is unavailable.')
if priority and priority == 2:
if not expire and not retry:
raise SaltInvocationError('Priority 2 requires pushover.expire and pushover.retry options.')
message = ('id: {0}\r\n'
'function: {1}\r\n'
'function args: {2}\r\n'
'jid: {3}\r\n'
'return: {4}\r\n').format(
ret.get('id'),
ret.get('fun'),
ret.get('fun_args'),
ret.get('jid'),
pprint.pformat(ret.get('return')))
result = _post_message(user=user,
device=device,
message=message,
title=title,
priority=priority,
expire=expire,
retry=retry,
sound=sound,
token=token)
log.debug('pushover result %s', result)
if not result['res']:
log.info('Error: %s', result['message'])
return | python | def returner(ret):
'''
Send an PushOver message with the data
'''
_options = _get_options(ret)
user = _options.get('user')
device = _options.get('device')
token = _options.get('token')
title = _options.get('title')
priority = _options.get('priority')
expire = _options.get('expire')
retry = _options.get('retry')
sound = _options.get('sound')
if not token:
raise SaltInvocationError('Pushover token is unavailable.')
if not user:
raise SaltInvocationError('Pushover user key is unavailable.')
if priority and priority == 2:
if not expire and not retry:
raise SaltInvocationError('Priority 2 requires pushover.expire and pushover.retry options.')
message = ('id: {0}\r\n'
'function: {1}\r\n'
'function args: {2}\r\n'
'jid: {3}\r\n'
'return: {4}\r\n').format(
ret.get('id'),
ret.get('fun'),
ret.get('fun_args'),
ret.get('jid'),
pprint.pformat(ret.get('return')))
result = _post_message(user=user,
device=device,
message=message,
title=title,
priority=priority,
expire=expire,
retry=retry,
sound=sound,
token=token)
log.debug('pushover result %s', result)
if not result['res']:
log.info('Error: %s', result['message'])
return | [
"def",
"returner",
"(",
"ret",
")",
":",
"_options",
"=",
"_get_options",
"(",
"ret",
")",
"user",
"=",
"_options",
".",
"get",
"(",
"'user'",
")",
"device",
"=",
"_options",
".",
"get",
"(",
"'device'",
")",
"token",
"=",
"_options",
".",
"get",
"("... | Send an PushOver message with the data | [
"Send",
"an",
"PushOver",
"message",
"with",
"the",
"data"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/pushover_returner.py#L201-L251 | train |
saltstack/salt | salt/loader.py | _format_entrypoint_target | def _format_entrypoint_target(ep):
'''
Makes a string describing the target of an EntryPoint object.
Base strongly on EntryPoint.__str__().
'''
s = ep.module_name
if ep.attrs:
s += ':' + '.'.join(ep.attrs)
return s | python | def _format_entrypoint_target(ep):
'''
Makes a string describing the target of an EntryPoint object.
Base strongly on EntryPoint.__str__().
'''
s = ep.module_name
if ep.attrs:
s += ':' + '.'.join(ep.attrs)
return s | [
"def",
"_format_entrypoint_target",
"(",
"ep",
")",
":",
"s",
"=",
"ep",
".",
"module_name",
"if",
"ep",
".",
"attrs",
":",
"s",
"+=",
"':'",
"+",
"'.'",
".",
"join",
"(",
"ep",
".",
"attrs",
")",
"return",
"s"
] | Makes a string describing the target of an EntryPoint object.
Base strongly on EntryPoint.__str__(). | [
"Makes",
"a",
"string",
"describing",
"the",
"target",
"of",
"an",
"EntryPoint",
"object",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L147-L156 | train |
saltstack/salt | salt/loader.py | minion_mods | def minion_mods(
opts,
context=None,
utils=None,
whitelist=None,
initial_load=False,
loaded_base_name=None,
notify=False,
static_modules=None,
proxy=None):
'''
Load execution modules
Returns a dictionary of execution modules appropriate for the current
system by evaluating the __virtual__() function in each module.
:param dict opts: The Salt options dictionary
:param dict context: A Salt context that should be made present inside
generated modules in __context__
:param dict utils: Utility functions which should be made available to
Salt modules in __utils__. See `utils_dirs` in
salt.config for additional information about
configuration.
:param list whitelist: A list of modules which should be whitelisted.
:param bool initial_load: Deprecated flag! Unused.
:param str loaded_base_name: A string marker for the loaded base name.
:param bool notify: Flag indicating that an event should be fired upon
completion of module loading.
.. code-block:: python
import salt.config
import salt.loader
__opts__ = salt.config.minion_config('/etc/salt/minion')
__grains__ = salt.loader.grains(__opts__)
__opts__['grains'] = __grains__
__utils__ = salt.loader.utils(__opts__)
__salt__ = salt.loader.minion_mods(__opts__, utils=__utils__)
__salt__['test.ping']()
'''
# TODO Publish documentation for module whitelisting
if not whitelist:
whitelist = opts.get('whitelist_modules', None)
ret = LazyLoader(
_module_dirs(opts, 'modules', 'module'),
opts,
tag='module',
pack={'__context__': context, '__utils__': utils, '__proxy__': proxy},
whitelist=whitelist,
loaded_base_name=loaded_base_name,
static_modules=static_modules,
)
ret.pack['__salt__'] = ret
# Load any provider overrides from the configuration file providers option
# Note: Providers can be pkg, service, user or group - not to be confused
# with cloud providers.
providers = opts.get('providers', False)
if providers and isinstance(providers, dict):
for mod in providers:
# sometimes providers opts is not to diverge modules but
# for other configuration
try:
funcs = raw_mod(opts, providers[mod], ret)
except TypeError:
break
else:
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(mod, func[func.rindex('.'):])
ret[f_key] = funcs[func]
if notify:
evt = salt.utils.event.get_event('minion', opts=opts, listen=False)
evt.fire_event({'complete': True},
tag=salt.defaults.events.MINION_MOD_COMPLETE)
return ret | python | def minion_mods(
opts,
context=None,
utils=None,
whitelist=None,
initial_load=False,
loaded_base_name=None,
notify=False,
static_modules=None,
proxy=None):
'''
Load execution modules
Returns a dictionary of execution modules appropriate for the current
system by evaluating the __virtual__() function in each module.
:param dict opts: The Salt options dictionary
:param dict context: A Salt context that should be made present inside
generated modules in __context__
:param dict utils: Utility functions which should be made available to
Salt modules in __utils__. See `utils_dirs` in
salt.config for additional information about
configuration.
:param list whitelist: A list of modules which should be whitelisted.
:param bool initial_load: Deprecated flag! Unused.
:param str loaded_base_name: A string marker for the loaded base name.
:param bool notify: Flag indicating that an event should be fired upon
completion of module loading.
.. code-block:: python
import salt.config
import salt.loader
__opts__ = salt.config.minion_config('/etc/salt/minion')
__grains__ = salt.loader.grains(__opts__)
__opts__['grains'] = __grains__
__utils__ = salt.loader.utils(__opts__)
__salt__ = salt.loader.minion_mods(__opts__, utils=__utils__)
__salt__['test.ping']()
'''
# TODO Publish documentation for module whitelisting
if not whitelist:
whitelist = opts.get('whitelist_modules', None)
ret = LazyLoader(
_module_dirs(opts, 'modules', 'module'),
opts,
tag='module',
pack={'__context__': context, '__utils__': utils, '__proxy__': proxy},
whitelist=whitelist,
loaded_base_name=loaded_base_name,
static_modules=static_modules,
)
ret.pack['__salt__'] = ret
# Load any provider overrides from the configuration file providers option
# Note: Providers can be pkg, service, user or group - not to be confused
# with cloud providers.
providers = opts.get('providers', False)
if providers and isinstance(providers, dict):
for mod in providers:
# sometimes providers opts is not to diverge modules but
# for other configuration
try:
funcs = raw_mod(opts, providers[mod], ret)
except TypeError:
break
else:
if funcs:
for func in funcs:
f_key = '{0}{1}'.format(mod, func[func.rindex('.'):])
ret[f_key] = funcs[func]
if notify:
evt = salt.utils.event.get_event('minion', opts=opts, listen=False)
evt.fire_event({'complete': True},
tag=salt.defaults.events.MINION_MOD_COMPLETE)
return ret | [
"def",
"minion_mods",
"(",
"opts",
",",
"context",
"=",
"None",
",",
"utils",
"=",
"None",
",",
"whitelist",
"=",
"None",
",",
"initial_load",
"=",
"False",
",",
"loaded_base_name",
"=",
"None",
",",
"notify",
"=",
"False",
",",
"static_modules",
"=",
"N... | Load execution modules
Returns a dictionary of execution modules appropriate for the current
system by evaluating the __virtual__() function in each module.
:param dict opts: The Salt options dictionary
:param dict context: A Salt context that should be made present inside
generated modules in __context__
:param dict utils: Utility functions which should be made available to
Salt modules in __utils__. See `utils_dirs` in
salt.config for additional information about
configuration.
:param list whitelist: A list of modules which should be whitelisted.
:param bool initial_load: Deprecated flag! Unused.
:param str loaded_base_name: A string marker for the loaded base name.
:param bool notify: Flag indicating that an event should be fired upon
completion of module loading.
.. code-block:: python
import salt.config
import salt.loader
__opts__ = salt.config.minion_config('/etc/salt/minion')
__grains__ = salt.loader.grains(__opts__)
__opts__['grains'] = __grains__
__utils__ = salt.loader.utils(__opts__)
__salt__ = salt.loader.minion_mods(__opts__, utils=__utils__)
__salt__['test.ping']() | [
"Load",
"execution",
"modules"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L205-L287 | train |
saltstack/salt | salt/loader.py | raw_mod | def raw_mod(opts, name, functions, mod='modules'):
'''
Returns a single module loaded raw and bypassing the __virtual__ function
.. code-block:: python
import salt.config
import salt.loader
__opts__ = salt.config.minion_config('/etc/salt/minion')
testmod = salt.loader.raw_mod(__opts__, 'test', None)
testmod['test.ping']()
'''
loader = LazyLoader(
_module_dirs(opts, mod, 'module'),
opts,
tag='rawmodule',
virtual_enable=False,
pack={'__salt__': functions},
)
# if we don't have the module, return an empty dict
if name not in loader.file_mapping:
return {}
loader._load_module(name) # load a single module (the one passed in)
return dict(loader._dict) | python | def raw_mod(opts, name, functions, mod='modules'):
'''
Returns a single module loaded raw and bypassing the __virtual__ function
.. code-block:: python
import salt.config
import salt.loader
__opts__ = salt.config.minion_config('/etc/salt/minion')
testmod = salt.loader.raw_mod(__opts__, 'test', None)
testmod['test.ping']()
'''
loader = LazyLoader(
_module_dirs(opts, mod, 'module'),
opts,
tag='rawmodule',
virtual_enable=False,
pack={'__salt__': functions},
)
# if we don't have the module, return an empty dict
if name not in loader.file_mapping:
return {}
loader._load_module(name) # load a single module (the one passed in)
return dict(loader._dict) | [
"def",
"raw_mod",
"(",
"opts",
",",
"name",
",",
"functions",
",",
"mod",
"=",
"'modules'",
")",
":",
"loader",
"=",
"LazyLoader",
"(",
"_module_dirs",
"(",
"opts",
",",
"mod",
",",
"'module'",
")",
",",
"opts",
",",
"tag",
"=",
"'rawmodule'",
",",
"... | Returns a single module loaded raw and bypassing the __virtual__ function
.. code-block:: python
import salt.config
import salt.loader
__opts__ = salt.config.minion_config('/etc/salt/minion')
testmod = salt.loader.raw_mod(__opts__, 'test', None)
testmod['test.ping']() | [
"Returns",
"a",
"single",
"module",
"loaded",
"raw",
"and",
"bypassing",
"the",
"__virtual__",
"function"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L290-L315 | train |
saltstack/salt | salt/loader.py | engines | def engines(opts, functions, runners, utils, proxy=None):
'''
Return the master services plugins
'''
pack = {'__salt__': functions,
'__runners__': runners,
'__proxy__': proxy,
'__utils__': utils}
return LazyLoader(
_module_dirs(opts, 'engines'),
opts,
tag='engines',
pack=pack,
) | python | def engines(opts, functions, runners, utils, proxy=None):
'''
Return the master services plugins
'''
pack = {'__salt__': functions,
'__runners__': runners,
'__proxy__': proxy,
'__utils__': utils}
return LazyLoader(
_module_dirs(opts, 'engines'),
opts,
tag='engines',
pack=pack,
) | [
"def",
"engines",
"(",
"opts",
",",
"functions",
",",
"runners",
",",
"utils",
",",
"proxy",
"=",
"None",
")",
":",
"pack",
"=",
"{",
"'__salt__'",
":",
"functions",
",",
"'__runners__'",
":",
"runners",
",",
"'__proxy__'",
":",
"proxy",
",",
"'__utils__... | Return the master services plugins | [
"Return",
"the",
"master",
"services",
"plugins"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L341-L354 | train |
saltstack/salt | salt/loader.py | proxy | def proxy(opts, functions=None, returners=None, whitelist=None, utils=None):
'''
Returns the proxy module for this salt-proxy-minion
'''
ret = LazyLoader(
_module_dirs(opts, 'proxy'),
opts,
tag='proxy',
pack={'__salt__': functions, '__ret__': returners, '__utils__': utils},
)
ret.pack['__proxy__'] = ret
return ret | python | def proxy(opts, functions=None, returners=None, whitelist=None, utils=None):
'''
Returns the proxy module for this salt-proxy-minion
'''
ret = LazyLoader(
_module_dirs(opts, 'proxy'),
opts,
tag='proxy',
pack={'__salt__': functions, '__ret__': returners, '__utils__': utils},
)
ret.pack['__proxy__'] = ret
return ret | [
"def",
"proxy",
"(",
"opts",
",",
"functions",
"=",
"None",
",",
"returners",
"=",
"None",
",",
"whitelist",
"=",
"None",
",",
"utils",
"=",
"None",
")",
":",
"ret",
"=",
"LazyLoader",
"(",
"_module_dirs",
"(",
"opts",
",",
"'proxy'",
")",
",",
"opts... | Returns the proxy module for this salt-proxy-minion | [
"Returns",
"the",
"proxy",
"module",
"for",
"this",
"salt",
"-",
"proxy",
"-",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L357-L370 | train |
saltstack/salt | salt/loader.py | returners | def returners(opts, functions, whitelist=None, context=None, proxy=None):
'''
Returns the returner modules
'''
return LazyLoader(
_module_dirs(opts, 'returners', 'returner'),
opts,
tag='returner',
whitelist=whitelist,
pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}},
) | python | def returners(opts, functions, whitelist=None, context=None, proxy=None):
'''
Returns the returner modules
'''
return LazyLoader(
_module_dirs(opts, 'returners', 'returner'),
opts,
tag='returner',
whitelist=whitelist,
pack={'__salt__': functions, '__context__': context, '__proxy__': proxy or {}},
) | [
"def",
"returners",
"(",
"opts",
",",
"functions",
",",
"whitelist",
"=",
"None",
",",
"context",
"=",
"None",
",",
"proxy",
"=",
"None",
")",
":",
"return",
"LazyLoader",
"(",
"_module_dirs",
"(",
"opts",
",",
"'returners'",
",",
"'returner'",
")",
",",... | Returns the returner modules | [
"Returns",
"the",
"returner",
"modules"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L373-L383 | train |
saltstack/salt | salt/loader.py | utils | def utils(opts, whitelist=None, context=None, proxy=proxy):
'''
Returns the utility modules
'''
return LazyLoader(
_module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'),
opts,
tag='utils',
whitelist=whitelist,
pack={'__context__': context, '__proxy__': proxy or {}},
) | python | def utils(opts, whitelist=None, context=None, proxy=proxy):
'''
Returns the utility modules
'''
return LazyLoader(
_module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'),
opts,
tag='utils',
whitelist=whitelist,
pack={'__context__': context, '__proxy__': proxy or {}},
) | [
"def",
"utils",
"(",
"opts",
",",
"whitelist",
"=",
"None",
",",
"context",
"=",
"None",
",",
"proxy",
"=",
"proxy",
")",
":",
"return",
"LazyLoader",
"(",
"_module_dirs",
"(",
"opts",
",",
"'utils'",
",",
"ext_type_dirs",
"=",
"'utils_dirs'",
")",
",",
... | Returns the utility modules | [
"Returns",
"the",
"utility",
"modules"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L386-L396 | train |
saltstack/salt | salt/loader.py | pillars | def pillars(opts, functions, context=None):
'''
Returns the pillars modules
'''
ret = LazyLoader(_module_dirs(opts, 'pillar'),
opts,
tag='pillar',
pack={'__salt__': functions,
'__context__': context,
'__utils__': utils(opts)})
ret.pack['__ext_pillar__'] = ret
return FilterDictWrapper(ret, '.ext_pillar') | python | def pillars(opts, functions, context=None):
'''
Returns the pillars modules
'''
ret = LazyLoader(_module_dirs(opts, 'pillar'),
opts,
tag='pillar',
pack={'__salt__': functions,
'__context__': context,
'__utils__': utils(opts)})
ret.pack['__ext_pillar__'] = ret
return FilterDictWrapper(ret, '.ext_pillar') | [
"def",
"pillars",
"(",
"opts",
",",
"functions",
",",
"context",
"=",
"None",
")",
":",
"ret",
"=",
"LazyLoader",
"(",
"_module_dirs",
"(",
"opts",
",",
"'pillar'",
")",
",",
"opts",
",",
"tag",
"=",
"'pillar'",
",",
"pack",
"=",
"{",
"'__salt__'",
"... | Returns the pillars modules | [
"Returns",
"the",
"pillars",
"modules"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L399-L410 | train |
saltstack/salt | salt/loader.py | tops | def tops(opts):
'''
Returns the tops modules
'''
if 'master_tops' not in opts:
return {}
whitelist = list(opts['master_tops'].keys())
ret = LazyLoader(
_module_dirs(opts, 'tops', 'top'),
opts,
tag='top',
whitelist=whitelist,
)
return FilterDictWrapper(ret, '.top') | python | def tops(opts):
'''
Returns the tops modules
'''
if 'master_tops' not in opts:
return {}
whitelist = list(opts['master_tops'].keys())
ret = LazyLoader(
_module_dirs(opts, 'tops', 'top'),
opts,
tag='top',
whitelist=whitelist,
)
return FilterDictWrapper(ret, '.top') | [
"def",
"tops",
"(",
"opts",
")",
":",
"if",
"'master_tops'",
"not",
"in",
"opts",
":",
"return",
"{",
"}",
"whitelist",
"=",
"list",
"(",
"opts",
"[",
"'master_tops'",
"]",
".",
"keys",
"(",
")",
")",
"ret",
"=",
"LazyLoader",
"(",
"_module_dirs",
"(... | Returns the tops modules | [
"Returns",
"the",
"tops",
"modules"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L413-L426 | train |
saltstack/salt | salt/loader.py | wheels | def wheels(opts, whitelist=None, context=None):
'''
Returns the wheels modules
'''
if context is None:
context = {}
return LazyLoader(
_module_dirs(opts, 'wheel'),
opts,
tag='wheel',
whitelist=whitelist,
pack={'__context__': context},
) | python | def wheels(opts, whitelist=None, context=None):
'''
Returns the wheels modules
'''
if context is None:
context = {}
return LazyLoader(
_module_dirs(opts, 'wheel'),
opts,
tag='wheel',
whitelist=whitelist,
pack={'__context__': context},
) | [
"def",
"wheels",
"(",
"opts",
",",
"whitelist",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"{",
"}",
"return",
"LazyLoader",
"(",
"_module_dirs",
"(",
"opts",
",",
"'wheel'",
")",
",",
"opt... | Returns the wheels modules | [
"Returns",
"the",
"wheels",
"modules"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L429-L441 | train |
saltstack/salt | salt/loader.py | outputters | def outputters(opts):
'''
Returns the outputters modules
:param dict opts: The Salt options dictionary
:returns: LazyLoader instance, with only outputters present in the keyspace
'''
ret = LazyLoader(
_module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'),
opts,
tag='output',
)
wrapped_ret = FilterDictWrapper(ret, '.output')
# TODO: this name seems terrible... __salt__ should always be execution mods
ret.pack['__salt__'] = wrapped_ret
return wrapped_ret | python | def outputters(opts):
'''
Returns the outputters modules
:param dict opts: The Salt options dictionary
:returns: LazyLoader instance, with only outputters present in the keyspace
'''
ret = LazyLoader(
_module_dirs(opts, 'output', ext_type_dirs='outputter_dirs'),
opts,
tag='output',
)
wrapped_ret = FilterDictWrapper(ret, '.output')
# TODO: this name seems terrible... __salt__ should always be execution mods
ret.pack['__salt__'] = wrapped_ret
return wrapped_ret | [
"def",
"outputters",
"(",
"opts",
")",
":",
"ret",
"=",
"LazyLoader",
"(",
"_module_dirs",
"(",
"opts",
",",
"'output'",
",",
"ext_type_dirs",
"=",
"'outputter_dirs'",
")",
",",
"opts",
",",
"tag",
"=",
"'output'",
",",
")",
"wrapped_ret",
"=",
"FilterDict... | Returns the outputters modules
:param dict opts: The Salt options dictionary
:returns: LazyLoader instance, with only outputters present in the keyspace | [
"Returns",
"the",
"outputters",
"modules"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L444-L459 | train |
saltstack/salt | salt/loader.py | auth | def auth(opts, whitelist=None):
'''
Returns the auth modules
:param dict opts: The Salt options dictionary
:returns: LazyLoader
'''
return LazyLoader(
_module_dirs(opts, 'auth'),
opts,
tag='auth',
whitelist=whitelist,
pack={'__salt__': minion_mods(opts)},
) | python | def auth(opts, whitelist=None):
'''
Returns the auth modules
:param dict opts: The Salt options dictionary
:returns: LazyLoader
'''
return LazyLoader(
_module_dirs(opts, 'auth'),
opts,
tag='auth',
whitelist=whitelist,
pack={'__salt__': minion_mods(opts)},
) | [
"def",
"auth",
"(",
"opts",
",",
"whitelist",
"=",
"None",
")",
":",
"return",
"LazyLoader",
"(",
"_module_dirs",
"(",
"opts",
",",
"'auth'",
")",
",",
"opts",
",",
"tag",
"=",
"'auth'",
",",
"whitelist",
"=",
"whitelist",
",",
"pack",
"=",
"{",
"'__... | Returns the auth modules
:param dict opts: The Salt options dictionary
:returns: LazyLoader | [
"Returns",
"the",
"auth",
"modules"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L488-L501 | train |
saltstack/salt | salt/loader.py | fileserver | def fileserver(opts, backends):
'''
Returns the file server modules
'''
return LazyLoader(_module_dirs(opts, 'fileserver'),
opts,
tag='fileserver',
whitelist=backends,
pack={'__utils__': utils(opts)}) | python | def fileserver(opts, backends):
'''
Returns the file server modules
'''
return LazyLoader(_module_dirs(opts, 'fileserver'),
opts,
tag='fileserver',
whitelist=backends,
pack={'__utils__': utils(opts)}) | [
"def",
"fileserver",
"(",
"opts",
",",
"backends",
")",
":",
"return",
"LazyLoader",
"(",
"_module_dirs",
"(",
"opts",
",",
"'fileserver'",
")",
",",
"opts",
",",
"tag",
"=",
"'fileserver'",
",",
"whitelist",
"=",
"backends",
",",
"pack",
"=",
"{",
"'__u... | Returns the file server modules | [
"Returns",
"the",
"file",
"server",
"modules"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L504-L512 | train |
saltstack/salt | salt/loader.py | roster | def roster(opts, runner=None, utils=None, whitelist=None):
'''
Returns the roster modules
'''
return LazyLoader(
_module_dirs(opts, 'roster'),
opts,
tag='roster',
whitelist=whitelist,
pack={
'__runner__': runner,
'__utils__': utils,
},
) | python | def roster(opts, runner=None, utils=None, whitelist=None):
'''
Returns the roster modules
'''
return LazyLoader(
_module_dirs(opts, 'roster'),
opts,
tag='roster',
whitelist=whitelist,
pack={
'__runner__': runner,
'__utils__': utils,
},
) | [
"def",
"roster",
"(",
"opts",
",",
"runner",
"=",
"None",
",",
"utils",
"=",
"None",
",",
"whitelist",
"=",
"None",
")",
":",
"return",
"LazyLoader",
"(",
"_module_dirs",
"(",
"opts",
",",
"'roster'",
")",
",",
"opts",
",",
"tag",
"=",
"'roster'",
",... | Returns the roster modules | [
"Returns",
"the",
"roster",
"modules"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L515-L528 | train |
saltstack/salt | salt/loader.py | thorium | def thorium(opts, functions, runners):
'''
Load the thorium runtime modules
'''
pack = {'__salt__': functions, '__runner__': runners, '__context__': {}}
ret = LazyLoader(_module_dirs(opts, 'thorium'),
opts,
tag='thorium',
pack=pack)
ret.pack['__thorium__'] = ret
return ret | python | def thorium(opts, functions, runners):
'''
Load the thorium runtime modules
'''
pack = {'__salt__': functions, '__runner__': runners, '__context__': {}}
ret = LazyLoader(_module_dirs(opts, 'thorium'),
opts,
tag='thorium',
pack=pack)
ret.pack['__thorium__'] = ret
return ret | [
"def",
"thorium",
"(",
"opts",
",",
"functions",
",",
"runners",
")",
":",
"pack",
"=",
"{",
"'__salt__'",
":",
"functions",
",",
"'__runner__'",
":",
"runners",
",",
"'__context__'",
":",
"{",
"}",
"}",
"ret",
"=",
"LazyLoader",
"(",
"_module_dirs",
"("... | Load the thorium runtime modules | [
"Load",
"the",
"thorium",
"runtime",
"modules"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L531-L541 | train |
saltstack/salt | salt/loader.py | states | def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None):
'''
Returns the state modules
:param dict opts: The Salt options dictionary
:param dict functions: A dictionary of minion modules, with module names as
keys and funcs as values.
.. code-block:: python
import salt.config
import salt.loader
__opts__ = salt.config.minion_config('/etc/salt/minion')
statemods = salt.loader.states(__opts__, None, None)
'''
if context is None:
context = {}
ret = LazyLoader(
_module_dirs(opts, 'states'),
opts,
tag='states',
pack={'__salt__': functions, '__proxy__': proxy or {}},
whitelist=whitelist,
)
ret.pack['__states__'] = ret
ret.pack['__utils__'] = utils
ret.pack['__serializers__'] = serializers
ret.pack['__context__'] = context
return ret | python | def states(opts, functions, utils, serializers, whitelist=None, proxy=None, context=None):
'''
Returns the state modules
:param dict opts: The Salt options dictionary
:param dict functions: A dictionary of minion modules, with module names as
keys and funcs as values.
.. code-block:: python
import salt.config
import salt.loader
__opts__ = salt.config.minion_config('/etc/salt/minion')
statemods = salt.loader.states(__opts__, None, None)
'''
if context is None:
context = {}
ret = LazyLoader(
_module_dirs(opts, 'states'),
opts,
tag='states',
pack={'__salt__': functions, '__proxy__': proxy or {}},
whitelist=whitelist,
)
ret.pack['__states__'] = ret
ret.pack['__utils__'] = utils
ret.pack['__serializers__'] = serializers
ret.pack['__context__'] = context
return ret | [
"def",
"states",
"(",
"opts",
",",
"functions",
",",
"utils",
",",
"serializers",
",",
"whitelist",
"=",
"None",
",",
"proxy",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"{",
"}",
"ret",
... | Returns the state modules
:param dict opts: The Salt options dictionary
:param dict functions: A dictionary of minion modules, with module names as
keys and funcs as values.
.. code-block:: python
import salt.config
import salt.loader
__opts__ = salt.config.minion_config('/etc/salt/minion')
statemods = salt.loader.states(__opts__, None, None) | [
"Returns",
"the",
"state",
"modules"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L544-L574 | train |
saltstack/salt | salt/loader.py | beacons | def beacons(opts, functions, context=None, proxy=None):
'''
Load the beacon modules
:param dict opts: The Salt options dictionary
:param dict functions: A dictionary of minion modules, with module names as
keys and funcs as values.
'''
return LazyLoader(
_module_dirs(opts, 'beacons'),
opts,
tag='beacons',
pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}},
virtual_funcs=[],
) | python | def beacons(opts, functions, context=None, proxy=None):
'''
Load the beacon modules
:param dict opts: The Salt options dictionary
:param dict functions: A dictionary of minion modules, with module names as
keys and funcs as values.
'''
return LazyLoader(
_module_dirs(opts, 'beacons'),
opts,
tag='beacons',
pack={'__context__': context, '__salt__': functions, '__proxy__': proxy or {}},
virtual_funcs=[],
) | [
"def",
"beacons",
"(",
"opts",
",",
"functions",
",",
"context",
"=",
"None",
",",
"proxy",
"=",
"None",
")",
":",
"return",
"LazyLoader",
"(",
"_module_dirs",
"(",
"opts",
",",
"'beacons'",
")",
",",
"opts",
",",
"tag",
"=",
"'beacons'",
",",
"pack",
... | Load the beacon modules
:param dict opts: The Salt options dictionary
:param dict functions: A dictionary of minion modules, with module names as
keys and funcs as values. | [
"Load",
"the",
"beacon",
"modules"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L577-L591 | train |
saltstack/salt | salt/loader.py | log_handlers | def log_handlers(opts):
'''
Returns the custom logging handler modules
:param dict opts: The Salt options dictionary
'''
ret = LazyLoader(
_module_dirs(
opts,
'log_handlers',
int_type='handlers',
base_path=os.path.join(SALT_BASE_PATH, 'log'),
),
opts,
tag='log_handlers',
)
return FilterDictWrapper(ret, '.setup_handlers') | python | def log_handlers(opts):
'''
Returns the custom logging handler modules
:param dict opts: The Salt options dictionary
'''
ret = LazyLoader(
_module_dirs(
opts,
'log_handlers',
int_type='handlers',
base_path=os.path.join(SALT_BASE_PATH, 'log'),
),
opts,
tag='log_handlers',
)
return FilterDictWrapper(ret, '.setup_handlers') | [
"def",
"log_handlers",
"(",
"opts",
")",
":",
"ret",
"=",
"LazyLoader",
"(",
"_module_dirs",
"(",
"opts",
",",
"'log_handlers'",
",",
"int_type",
"=",
"'handlers'",
",",
"base_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"SALT_BASE_PATH",
",",
"'log'",... | Returns the custom logging handler modules
:param dict opts: The Salt options dictionary | [
"Returns",
"the",
"custom",
"logging",
"handler",
"modules"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L594-L610 | train |
saltstack/salt | salt/loader.py | ssh_wrapper | def ssh_wrapper(opts, functions=None, context=None):
'''
Returns the custom logging handler modules
'''
return LazyLoader(
_module_dirs(
opts,
'wrapper',
base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')),
),
opts,
tag='wrapper',
pack={
'__salt__': functions,
'__grains__': opts.get('grains', {}),
'__pillar__': opts.get('pillar', {}),
'__context__': context,
},
) | python | def ssh_wrapper(opts, functions=None, context=None):
'''
Returns the custom logging handler modules
'''
return LazyLoader(
_module_dirs(
opts,
'wrapper',
base_path=os.path.join(SALT_BASE_PATH, os.path.join('client', 'ssh')),
),
opts,
tag='wrapper',
pack={
'__salt__': functions,
'__grains__': opts.get('grains', {}),
'__pillar__': opts.get('pillar', {}),
'__context__': context,
},
) | [
"def",
"ssh_wrapper",
"(",
"opts",
",",
"functions",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"return",
"LazyLoader",
"(",
"_module_dirs",
"(",
"opts",
",",
"'wrapper'",
",",
"base_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"SALT_BASE_PA... | Returns the custom logging handler modules | [
"Returns",
"the",
"custom",
"logging",
"handler",
"modules"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L613-L631 | train |
saltstack/salt | salt/loader.py | render | def render(opts, functions, states=None, proxy=None, context=None):
'''
Returns the render modules
'''
if context is None:
context = {}
pack = {'__salt__': functions,
'__grains__': opts.get('grains', {}),
'__context__': context}
if states:
pack['__states__'] = states
pack['__proxy__'] = proxy or {}
ret = LazyLoader(
_module_dirs(
opts,
'renderers',
'render',
ext_type_dirs='render_dirs',
),
opts,
tag='render',
pack=pack,
)
rend = FilterDictWrapper(ret, '.render')
if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']):
err = ('The renderer {0} is unavailable, this error is often because '
'the needed software is unavailable'.format(opts['renderer']))
log.critical(err)
raise LoaderError(err)
return rend | python | def render(opts, functions, states=None, proxy=None, context=None):
'''
Returns the render modules
'''
if context is None:
context = {}
pack = {'__salt__': functions,
'__grains__': opts.get('grains', {}),
'__context__': context}
if states:
pack['__states__'] = states
pack['__proxy__'] = proxy or {}
ret = LazyLoader(
_module_dirs(
opts,
'renderers',
'render',
ext_type_dirs='render_dirs',
),
opts,
tag='render',
pack=pack,
)
rend = FilterDictWrapper(ret, '.render')
if not check_render_pipe_str(opts['renderer'], rend, opts['renderer_blacklist'], opts['renderer_whitelist']):
err = ('The renderer {0} is unavailable, this error is often because '
'the needed software is unavailable'.format(opts['renderer']))
log.critical(err)
raise LoaderError(err)
return rend | [
"def",
"render",
"(",
"opts",
",",
"functions",
",",
"states",
"=",
"None",
",",
"proxy",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"{",
"}",
"pack",
"=",
"{",
"'__salt__'",
":",
"functi... | Returns the render modules | [
"Returns",
"the",
"render",
"modules"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L634-L666 | train |
saltstack/salt | salt/loader.py | grain_funcs | def grain_funcs(opts, proxy=None):
'''
Returns the grain functions
.. code-block:: python
import salt.config
import salt.loader
__opts__ = salt.config.minion_config('/etc/salt/minion')
grainfuncs = salt.loader.grain_funcs(__opts__)
'''
ret = LazyLoader(
_module_dirs(
opts,
'grains',
'grain',
ext_type_dirs='grains_dirs',
),
opts,
tag='grains',
)
ret.pack['__utils__'] = utils(opts, proxy=proxy)
return ret | python | def grain_funcs(opts, proxy=None):
'''
Returns the grain functions
.. code-block:: python
import salt.config
import salt.loader
__opts__ = salt.config.minion_config('/etc/salt/minion')
grainfuncs = salt.loader.grain_funcs(__opts__)
'''
ret = LazyLoader(
_module_dirs(
opts,
'grains',
'grain',
ext_type_dirs='grains_dirs',
),
opts,
tag='grains',
)
ret.pack['__utils__'] = utils(opts, proxy=proxy)
return ret | [
"def",
"grain_funcs",
"(",
"opts",
",",
"proxy",
"=",
"None",
")",
":",
"ret",
"=",
"LazyLoader",
"(",
"_module_dirs",
"(",
"opts",
",",
"'grains'",
",",
"'grain'",
",",
"ext_type_dirs",
"=",
"'grains_dirs'",
",",
")",
",",
"opts",
",",
"tag",
"=",
"'g... | Returns the grain functions
.. code-block:: python
import salt.config
import salt.loader
__opts__ = salt.config.minion_config('/etc/salt/minion')
grainfuncs = salt.loader.grain_funcs(__opts__) | [
"Returns",
"the",
"grain",
"functions"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L669-L692 | train |
saltstack/salt | salt/loader.py | _load_cached_grains | def _load_cached_grains(opts, cfn):
'''
Returns the grains cached in cfn, or None if the cache is too old or is
corrupted.
'''
if not os.path.isfile(cfn):
log.debug('Grains cache file does not exist.')
return None
grains_cache_age = int(time.time() - os.path.getmtime(cfn))
if grains_cache_age > opts.get('grains_cache_expiration', 300):
log.debug(
'Grains cache last modified %s seconds ago and cache '
'expiration is set to %s. Grains cache expired. '
'Refreshing.',
grains_cache_age, opts.get('grains_cache_expiration', 300)
)
return None
if opts.get('refresh_grains_cache', False):
log.debug('refresh_grains_cache requested, Refreshing.')
return None
log.debug('Retrieving grains from cache')
try:
serial = salt.payload.Serial(opts)
with salt.utils.files.fopen(cfn, 'rb') as fp_:
cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True)
if not cached_grains:
log.debug('Cached grains are empty, cache might be corrupted. Refreshing.')
return None
return cached_grains
except (IOError, OSError):
return None | python | def _load_cached_grains(opts, cfn):
'''
Returns the grains cached in cfn, or None if the cache is too old or is
corrupted.
'''
if not os.path.isfile(cfn):
log.debug('Grains cache file does not exist.')
return None
grains_cache_age = int(time.time() - os.path.getmtime(cfn))
if grains_cache_age > opts.get('grains_cache_expiration', 300):
log.debug(
'Grains cache last modified %s seconds ago and cache '
'expiration is set to %s. Grains cache expired. '
'Refreshing.',
grains_cache_age, opts.get('grains_cache_expiration', 300)
)
return None
if opts.get('refresh_grains_cache', False):
log.debug('refresh_grains_cache requested, Refreshing.')
return None
log.debug('Retrieving grains from cache')
try:
serial = salt.payload.Serial(opts)
with salt.utils.files.fopen(cfn, 'rb') as fp_:
cached_grains = salt.utils.data.decode(serial.load(fp_), preserve_tuples=True)
if not cached_grains:
log.debug('Cached grains are empty, cache might be corrupted. Refreshing.')
return None
return cached_grains
except (IOError, OSError):
return None | [
"def",
"_load_cached_grains",
"(",
"opts",
",",
"cfn",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"cfn",
")",
":",
"log",
".",
"debug",
"(",
"'Grains cache file does not exist.'",
")",
"return",
"None",
"grains_cache_age",
"=",
"int",
"(... | Returns the grains cached in cfn, or None if the cache is too old or is
corrupted. | [
"Returns",
"the",
"grains",
"cached",
"in",
"cfn",
"or",
"None",
"if",
"the",
"cache",
"is",
"too",
"old",
"or",
"is",
"corrupted",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L695-L729 | train |
saltstack/salt | salt/loader.py | grains | def grains(opts, force_refresh=False, proxy=None):
'''
Return the functions for the dynamic grains and the values for the static
grains.
Since grains are computed early in the startup process, grains functions
do not have __salt__ or __proxy__ available. At proxy-minion startup,
this function is called with the proxymodule LazyLoader object so grains
functions can communicate with their controlled device.
.. code-block:: python
import salt.config
import salt.loader
__opts__ = salt.config.minion_config('/etc/salt/minion')
__grains__ = salt.loader.grains(__opts__)
print __grains__['id']
'''
# Need to re-import salt.config, somehow it got lost when a minion is starting
import salt.config
# if we have no grains, lets try loading from disk (TODO: move to decorator?)
cfn = os.path.join(
opts['cachedir'],
'grains.cache.p'
)
if not force_refresh and opts.get('grains_cache', False):
cached_grains = _load_cached_grains(opts, cfn)
if cached_grains:
return cached_grains
else:
log.debug('Grains refresh requested. Refreshing grains.')
if opts.get('skip_grains', False):
return {}
grains_deep_merge = opts.get('grains_deep_merge', False) is True
if 'conf_file' in opts:
pre_opts = {}
pre_opts.update(salt.config.load_config(
opts['conf_file'], 'SALT_MINION_CONFIG',
salt.config.DEFAULT_MINION_OPTS['conf_file']
))
default_include = pre_opts.get(
'default_include', opts['default_include']
)
include = pre_opts.get('include', [])
pre_opts.update(salt.config.include_config(
default_include, opts['conf_file'], verbose=False
))
pre_opts.update(salt.config.include_config(
include, opts['conf_file'], verbose=True
))
if 'grains' in pre_opts:
opts['grains'] = pre_opts['grains']
else:
opts['grains'] = {}
else:
opts['grains'] = {}
grains_data = {}
blist = opts.get('grains_blacklist', [])
funcs = grain_funcs(opts, proxy=proxy)
if force_refresh: # if we refresh, lets reload grain modules
funcs.clear()
# Run core grains
for key in funcs:
if not key.startswith('core.'):
continue
log.trace('Loading %s grain', key)
ret = funcs[key]()
if not isinstance(ret, dict):
continue
if blist:
for key in list(ret):
for block in blist:
if salt.utils.stringutils.expr_match(key, block):
del ret[key]
log.trace('Filtering %s grain', key)
if not ret:
continue
if grains_deep_merge:
salt.utils.dictupdate.update(grains_data, ret)
else:
grains_data.update(ret)
# Run the rest of the grains
for key in funcs:
if key.startswith('core.') or key == '_errors':
continue
try:
# Grains are loaded too early to take advantage of the injected
# __proxy__ variable. Pass an instance of that LazyLoader
# here instead to grains functions if the grains functions take
# one parameter. Then the grains can have access to the
# proxymodule for retrieving information from the connected
# device.
log.trace('Loading %s grain', key)
parameters = salt.utils.args.get_function_argspec(funcs[key]).args
kwargs = {}
if 'proxy' in parameters:
kwargs['proxy'] = proxy
if 'grains' in parameters:
kwargs['grains'] = grains_data
ret = funcs[key](**kwargs)
except Exception:
if salt.utils.platform.is_proxy():
log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.')
log.critical(
'Failed to load grains defined in grain file %s in '
'function %s, error:\n', key, funcs[key],
exc_info=True
)
continue
if not isinstance(ret, dict):
continue
if blist:
for key in list(ret):
for block in blist:
if salt.utils.stringutils.expr_match(key, block):
del ret[key]
log.trace('Filtering %s grain', key)
if not ret:
continue
if grains_deep_merge:
salt.utils.dictupdate.update(grains_data, ret)
else:
grains_data.update(ret)
if opts.get('proxy_merge_grains_in_module', True) and proxy:
try:
proxytype = proxy.opts['proxy']['proxytype']
if proxytype + '.grains' in proxy:
if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized']():
try:
proxytype = proxy.opts['proxy']['proxytype']
ret = proxy[proxytype + '.grains']()
if grains_deep_merge:
salt.utils.dictupdate.update(grains_data, ret)
else:
grains_data.update(ret)
except Exception:
log.critical('Failed to run proxy\'s grains function!',
exc_info=True
)
except KeyError:
pass
grains_data.update(opts['grains'])
# Write cache if enabled
if opts.get('grains_cache', False):
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Late import
import salt.modules.cmdmod
# Make sure cache file isn't read-only
salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn))
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
serial = salt.payload.Serial(opts)
serial.dump(grains_data, fp_)
except TypeError as e:
log.error('Failed to serialize grains cache: %s', e)
raise # re-throw for cleanup
except Exception as e:
log.error('Unable to write to grains cache file %s: %s', cfn, e)
# Based on the original exception, the file may or may not have been
# created. If it was, we will remove it now, as the exception means
# the serialized data is not to be trusted, no matter what the
# exception is.
if os.path.isfile(cfn):
os.unlink(cfn)
if grains_deep_merge:
salt.utils.dictupdate.update(grains_data, opts['grains'])
else:
grains_data.update(opts['grains'])
return salt.utils.data.decode(grains_data, preserve_tuples=True) | python | def grains(opts, force_refresh=False, proxy=None):
'''
Return the functions for the dynamic grains and the values for the static
grains.
Since grains are computed early in the startup process, grains functions
do not have __salt__ or __proxy__ available. At proxy-minion startup,
this function is called with the proxymodule LazyLoader object so grains
functions can communicate with their controlled device.
.. code-block:: python
import salt.config
import salt.loader
__opts__ = salt.config.minion_config('/etc/salt/minion')
__grains__ = salt.loader.grains(__opts__)
print __grains__['id']
'''
# Need to re-import salt.config, somehow it got lost when a minion is starting
import salt.config
# if we have no grains, lets try loading from disk (TODO: move to decorator?)
cfn = os.path.join(
opts['cachedir'],
'grains.cache.p'
)
if not force_refresh and opts.get('grains_cache', False):
cached_grains = _load_cached_grains(opts, cfn)
if cached_grains:
return cached_grains
else:
log.debug('Grains refresh requested. Refreshing grains.')
if opts.get('skip_grains', False):
return {}
grains_deep_merge = opts.get('grains_deep_merge', False) is True
if 'conf_file' in opts:
pre_opts = {}
pre_opts.update(salt.config.load_config(
opts['conf_file'], 'SALT_MINION_CONFIG',
salt.config.DEFAULT_MINION_OPTS['conf_file']
))
default_include = pre_opts.get(
'default_include', opts['default_include']
)
include = pre_opts.get('include', [])
pre_opts.update(salt.config.include_config(
default_include, opts['conf_file'], verbose=False
))
pre_opts.update(salt.config.include_config(
include, opts['conf_file'], verbose=True
))
if 'grains' in pre_opts:
opts['grains'] = pre_opts['grains']
else:
opts['grains'] = {}
else:
opts['grains'] = {}
grains_data = {}
blist = opts.get('grains_blacklist', [])
funcs = grain_funcs(opts, proxy=proxy)
if force_refresh: # if we refresh, lets reload grain modules
funcs.clear()
# Run core grains
for key in funcs:
if not key.startswith('core.'):
continue
log.trace('Loading %s grain', key)
ret = funcs[key]()
if not isinstance(ret, dict):
continue
if blist:
for key in list(ret):
for block in blist:
if salt.utils.stringutils.expr_match(key, block):
del ret[key]
log.trace('Filtering %s grain', key)
if not ret:
continue
if grains_deep_merge:
salt.utils.dictupdate.update(grains_data, ret)
else:
grains_data.update(ret)
# Run the rest of the grains
for key in funcs:
if key.startswith('core.') or key == '_errors':
continue
try:
# Grains are loaded too early to take advantage of the injected
# __proxy__ variable. Pass an instance of that LazyLoader
# here instead to grains functions if the grains functions take
# one parameter. Then the grains can have access to the
# proxymodule for retrieving information from the connected
# device.
log.trace('Loading %s grain', key)
parameters = salt.utils.args.get_function_argspec(funcs[key]).args
kwargs = {}
if 'proxy' in parameters:
kwargs['proxy'] = proxy
if 'grains' in parameters:
kwargs['grains'] = grains_data
ret = funcs[key](**kwargs)
except Exception:
if salt.utils.platform.is_proxy():
log.info('The following CRITICAL message may not be an error; the proxy may not be completely established yet.')
log.critical(
'Failed to load grains defined in grain file %s in '
'function %s, error:\n', key, funcs[key],
exc_info=True
)
continue
if not isinstance(ret, dict):
continue
if blist:
for key in list(ret):
for block in blist:
if salt.utils.stringutils.expr_match(key, block):
del ret[key]
log.trace('Filtering %s grain', key)
if not ret:
continue
if grains_deep_merge:
salt.utils.dictupdate.update(grains_data, ret)
else:
grains_data.update(ret)
if opts.get('proxy_merge_grains_in_module', True) and proxy:
try:
proxytype = proxy.opts['proxy']['proxytype']
if proxytype + '.grains' in proxy:
if proxytype + '.initialized' in proxy and proxy[proxytype + '.initialized']():
try:
proxytype = proxy.opts['proxy']['proxytype']
ret = proxy[proxytype + '.grains']()
if grains_deep_merge:
salt.utils.dictupdate.update(grains_data, ret)
else:
grains_data.update(ret)
except Exception:
log.critical('Failed to run proxy\'s grains function!',
exc_info=True
)
except KeyError:
pass
grains_data.update(opts['grains'])
# Write cache if enabled
if opts.get('grains_cache', False):
with salt.utils.files.set_umask(0o077):
try:
if salt.utils.platform.is_windows():
# Late import
import salt.modules.cmdmod
# Make sure cache file isn't read-only
salt.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn))
with salt.utils.files.fopen(cfn, 'w+b') as fp_:
try:
serial = salt.payload.Serial(opts)
serial.dump(grains_data, fp_)
except TypeError as e:
log.error('Failed to serialize grains cache: %s', e)
raise # re-throw for cleanup
except Exception as e:
log.error('Unable to write to grains cache file %s: %s', cfn, e)
# Based on the original exception, the file may or may not have been
# created. If it was, we will remove it now, as the exception means
# the serialized data is not to be trusted, no matter what the
# exception is.
if os.path.isfile(cfn):
os.unlink(cfn)
if grains_deep_merge:
salt.utils.dictupdate.update(grains_data, opts['grains'])
else:
grains_data.update(opts['grains'])
return salt.utils.data.decode(grains_data, preserve_tuples=True) | [
"def",
"grains",
"(",
"opts",
",",
"force_refresh",
"=",
"False",
",",
"proxy",
"=",
"None",
")",
":",
"# Need to re-import salt.config, somehow it got lost when a minion is starting",
"import",
"salt",
".",
"config",
"# if we have no grains, lets try loading from disk (TODO: m... | Return the functions for the dynamic grains and the values for the static
grains.
Since grains are computed early in the startup process, grains functions
do not have __salt__ or __proxy__ available. At proxy-minion startup,
this function is called with the proxymodule LazyLoader object so grains
functions can communicate with their controlled device.
.. code-block:: python
import salt.config
import salt.loader
__opts__ = salt.config.minion_config('/etc/salt/minion')
__grains__ = salt.loader.grains(__opts__)
print __grains__['id'] | [
"Return",
"the",
"functions",
"for",
"the",
"dynamic",
"grains",
"and",
"the",
"values",
"for",
"the",
"static",
"grains",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L732-L909 | train |
saltstack/salt | salt/loader.py | call | def call(fun, **kwargs):
'''
Directly call a function inside a loader directory
'''
args = kwargs.get('args', [])
dirs = kwargs.get('dirs', [])
funcs = LazyLoader(
[os.path.join(SALT_BASE_PATH, 'modules')] + dirs,
None,
tag='modules',
virtual_enable=False,
)
return funcs[fun](*args) | python | def call(fun, **kwargs):
'''
Directly call a function inside a loader directory
'''
args = kwargs.get('args', [])
dirs = kwargs.get('dirs', [])
funcs = LazyLoader(
[os.path.join(SALT_BASE_PATH, 'modules')] + dirs,
None,
tag='modules',
virtual_enable=False,
)
return funcs[fun](*args) | [
"def",
"call",
"(",
"fun",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"kwargs",
".",
"get",
"(",
"'args'",
",",
"[",
"]",
")",
"dirs",
"=",
"kwargs",
".",
"get",
"(",
"'dirs'",
",",
"[",
"]",
")",
"funcs",
"=",
"LazyLoader",
"(",
"[",
"o... | Directly call a function inside a loader directory | [
"Directly",
"call",
"a",
"function",
"inside",
"a",
"loader",
"directory"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L913-L926 | train |
saltstack/salt | salt/loader.py | runner | def runner(opts, utils=None, context=None, whitelist=None):
'''
Directly call a function inside a loader directory
'''
if utils is None:
utils = {}
if context is None:
context = {}
ret = LazyLoader(
_module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'),
opts,
tag='runners',
pack={'__utils__': utils, '__context__': context},
whitelist=whitelist,
)
# TODO: change from __salt__ to something else, we overload __salt__ too much
ret.pack['__salt__'] = ret
return ret | python | def runner(opts, utils=None, context=None, whitelist=None):
'''
Directly call a function inside a loader directory
'''
if utils is None:
utils = {}
if context is None:
context = {}
ret = LazyLoader(
_module_dirs(opts, 'runners', 'runner', ext_type_dirs='runner_dirs'),
opts,
tag='runners',
pack={'__utils__': utils, '__context__': context},
whitelist=whitelist,
)
# TODO: change from __salt__ to something else, we overload __salt__ too much
ret.pack['__salt__'] = ret
return ret | [
"def",
"runner",
"(",
"opts",
",",
"utils",
"=",
"None",
",",
"context",
"=",
"None",
",",
"whitelist",
"=",
"None",
")",
":",
"if",
"utils",
"is",
"None",
":",
"utils",
"=",
"{",
"}",
"if",
"context",
"is",
"None",
":",
"context",
"=",
"{",
"}",... | Directly call a function inside a loader directory | [
"Directly",
"call",
"a",
"function",
"inside",
"a",
"loader",
"directory"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L929-L946 | train |
saltstack/salt | salt/loader.py | sdb | def sdb(opts, functions=None, whitelist=None, utils=None):
'''
Make a very small database call
'''
if utils is None:
utils = {}
return LazyLoader(
_module_dirs(opts, 'sdb'),
opts,
tag='sdb',
pack={
'__sdb__': functions,
'__opts__': opts,
'__utils__': utils,
'__salt__': minion_mods(opts, utils),
},
whitelist=whitelist,
) | python | def sdb(opts, functions=None, whitelist=None, utils=None):
'''
Make a very small database call
'''
if utils is None:
utils = {}
return LazyLoader(
_module_dirs(opts, 'sdb'),
opts,
tag='sdb',
pack={
'__sdb__': functions,
'__opts__': opts,
'__utils__': utils,
'__salt__': minion_mods(opts, utils),
},
whitelist=whitelist,
) | [
"def",
"sdb",
"(",
"opts",
",",
"functions",
"=",
"None",
",",
"whitelist",
"=",
"None",
",",
"utils",
"=",
"None",
")",
":",
"if",
"utils",
"is",
"None",
":",
"utils",
"=",
"{",
"}",
"return",
"LazyLoader",
"(",
"_module_dirs",
"(",
"opts",
",",
"... | Make a very small database call | [
"Make",
"a",
"very",
"small",
"database",
"call"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L960-L978 | train |
saltstack/salt | salt/loader.py | pkgdb | def pkgdb(opts):
'''
Return modules for SPM's package database
.. versionadded:: 2015.8.0
'''
return LazyLoader(
_module_dirs(
opts,
'pkgdb',
base_path=os.path.join(SALT_BASE_PATH, 'spm')
),
opts,
tag='pkgdb'
) | python | def pkgdb(opts):
'''
Return modules for SPM's package database
.. versionadded:: 2015.8.0
'''
return LazyLoader(
_module_dirs(
opts,
'pkgdb',
base_path=os.path.join(SALT_BASE_PATH, 'spm')
),
opts,
tag='pkgdb'
) | [
"def",
"pkgdb",
"(",
"opts",
")",
":",
"return",
"LazyLoader",
"(",
"_module_dirs",
"(",
"opts",
",",
"'pkgdb'",
",",
"base_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"SALT_BASE_PATH",
",",
"'spm'",
")",
")",
",",
"opts",
",",
"tag",
"=",
"'pkg... | Return modules for SPM's package database
.. versionadded:: 2015.8.0 | [
"Return",
"modules",
"for",
"SPM",
"s",
"package",
"database"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L981-L995 | train |
saltstack/salt | salt/loader.py | clouds | def clouds(opts):
'''
Return the cloud functions
'''
# Let's bring __active_provider_name__, defaulting to None, to all cloud
# drivers. This will get temporarily updated/overridden with a context
# manager when needed.
functions = LazyLoader(
_module_dirs(opts,
'clouds',
'cloud',
base_path=os.path.join(SALT_BASE_PATH, 'cloud'),
int_type='clouds'),
opts,
tag='clouds',
pack={'__utils__': salt.loader.utils(opts),
'__active_provider_name__': None},
)
for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED:
log.trace(
'\'%s\' has been marked as not supported. Removing from the '
'list of supported cloud functions', funcname
)
functions.pop(funcname, None)
return functions | python | def clouds(opts):
'''
Return the cloud functions
'''
# Let's bring __active_provider_name__, defaulting to None, to all cloud
# drivers. This will get temporarily updated/overridden with a context
# manager when needed.
functions = LazyLoader(
_module_dirs(opts,
'clouds',
'cloud',
base_path=os.path.join(SALT_BASE_PATH, 'cloud'),
int_type='clouds'),
opts,
tag='clouds',
pack={'__utils__': salt.loader.utils(opts),
'__active_provider_name__': None},
)
for funcname in LIBCLOUD_FUNCS_NOT_SUPPORTED:
log.trace(
'\'%s\' has been marked as not supported. Removing from the '
'list of supported cloud functions', funcname
)
functions.pop(funcname, None)
return functions | [
"def",
"clouds",
"(",
"opts",
")",
":",
"# Let's bring __active_provider_name__, defaulting to None, to all cloud",
"# drivers. This will get temporarily updated/overridden with a context",
"# manager when needed.",
"functions",
"=",
"LazyLoader",
"(",
"_module_dirs",
"(",
"opts",
",... | Return the cloud functions | [
"Return",
"the",
"cloud",
"functions"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1015-L1039 | train |
saltstack/salt | salt/loader.py | executors | def executors(opts, functions=None, context=None, proxy=None):
'''
Returns the executor modules
'''
executors = LazyLoader(
_module_dirs(opts, 'executors', 'executor'),
opts,
tag='executor',
pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}},
)
executors.pack['__executors__'] = executors
return executors | python | def executors(opts, functions=None, context=None, proxy=None):
'''
Returns the executor modules
'''
executors = LazyLoader(
_module_dirs(opts, 'executors', 'executor'),
opts,
tag='executor',
pack={'__salt__': functions, '__context__': context or {}, '__proxy__': proxy or {}},
)
executors.pack['__executors__'] = executors
return executors | [
"def",
"executors",
"(",
"opts",
",",
"functions",
"=",
"None",
",",
"context",
"=",
"None",
",",
"proxy",
"=",
"None",
")",
":",
"executors",
"=",
"LazyLoader",
"(",
"_module_dirs",
"(",
"opts",
",",
"'executors'",
",",
"'executor'",
")",
",",
"opts",
... | Returns the executor modules | [
"Returns",
"the",
"executor",
"modules"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1053-L1064 | train |
saltstack/salt | salt/loader.py | cache | def cache(opts, serial):
'''
Returns the returner modules
'''
return LazyLoader(
_module_dirs(opts, 'cache', 'cache'),
opts,
tag='cache',
pack={'__opts__': opts, '__context__': {'serial': serial}},
) | python | def cache(opts, serial):
'''
Returns the returner modules
'''
return LazyLoader(
_module_dirs(opts, 'cache', 'cache'),
opts,
tag='cache',
pack={'__opts__': opts, '__context__': {'serial': serial}},
) | [
"def",
"cache",
"(",
"opts",
",",
"serial",
")",
":",
"return",
"LazyLoader",
"(",
"_module_dirs",
"(",
"opts",
",",
"'cache'",
",",
"'cache'",
")",
",",
"opts",
",",
"tag",
"=",
"'cache'",
",",
"pack",
"=",
"{",
"'__opts__'",
":",
"opts",
",",
"'__c... | Returns the returner modules | [
"Returns",
"the",
"returner",
"modules"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1067-L1076 | train |
saltstack/salt | salt/loader.py | _inject_into_mod | def _inject_into_mod(mod, name, value, force_lock=False):
'''
Inject a variable into a module. This is used to inject "globals" like
``__salt__``, ``__pillar``, or ``grains``.
Instead of injecting the value directly, a ``ThreadLocalProxy`` is created.
If such a proxy is already present under the specified name, it is updated
with the new value. This update only affects the current thread, so that
the same name can refer to different values depending on the thread of
execution.
This is important for data that is not truly global. For example, pillar
data might be dynamically overriden through function parameters and thus
the actual values available in pillar might depend on the thread that is
calling a module.
mod:
module object into which the value is going to be injected.
name:
name of the variable that is injected into the module.
value:
value that is injected into the variable. The value is not injected
directly, but instead set as the new reference of the proxy that has
been created for the variable.
force_lock:
whether the lock should be acquired before checking whether a proxy
object for the specified name has already been injected into the
module. If ``False`` (the default), this function checks for the
module's variable without acquiring the lock and only acquires the lock
if a new proxy has to be created and injected.
'''
old_value = getattr(mod, name, None)
# We use a double-checked locking scheme in order to avoid taking the lock
# when a proxy object has already been injected.
# In most programming languages, double-checked locking is considered
# unsafe when used without explicit memory barriers because one might read
# an uninitialized value. In CPython it is safe due to the global
# interpreter lock (GIL). In Python implementations that do not have the
# GIL, it could be unsafe, but at least Jython also guarantees that (for
# Python objects) memory is not corrupted when writing and reading without
# explicit synchronization
# (http://www.jython.org/jythonbook/en/1.0/Concurrency.html).
# Please note that in order to make this code safe in a runtime environment
# that does not make this guarantees, it is not sufficient. The
# ThreadLocalProxy must also be created with fallback_to_shared set to
# False or a lock must be added to the ThreadLocalProxy.
if force_lock:
with _inject_into_mod.lock:
if isinstance(old_value, ThreadLocalProxy):
ThreadLocalProxy.set_reference(old_value, value)
else:
setattr(mod, name, ThreadLocalProxy(value, True))
else:
if isinstance(old_value, ThreadLocalProxy):
ThreadLocalProxy.set_reference(old_value, value)
else:
_inject_into_mod(mod, name, value, True) | python | def _inject_into_mod(mod, name, value, force_lock=False):
'''
Inject a variable into a module. This is used to inject "globals" like
``__salt__``, ``__pillar``, or ``grains``.
Instead of injecting the value directly, a ``ThreadLocalProxy`` is created.
If such a proxy is already present under the specified name, it is updated
with the new value. This update only affects the current thread, so that
the same name can refer to different values depending on the thread of
execution.
This is important for data that is not truly global. For example, pillar
data might be dynamically overriden through function parameters and thus
the actual values available in pillar might depend on the thread that is
calling a module.
mod:
module object into which the value is going to be injected.
name:
name of the variable that is injected into the module.
value:
value that is injected into the variable. The value is not injected
directly, but instead set as the new reference of the proxy that has
been created for the variable.
force_lock:
whether the lock should be acquired before checking whether a proxy
object for the specified name has already been injected into the
module. If ``False`` (the default), this function checks for the
module's variable without acquiring the lock and only acquires the lock
if a new proxy has to be created and injected.
'''
old_value = getattr(mod, name, None)
# We use a double-checked locking scheme in order to avoid taking the lock
# when a proxy object has already been injected.
# In most programming languages, double-checked locking is considered
# unsafe when used without explicit memory barriers because one might read
# an uninitialized value. In CPython it is safe due to the global
# interpreter lock (GIL). In Python implementations that do not have the
# GIL, it could be unsafe, but at least Jython also guarantees that (for
# Python objects) memory is not corrupted when writing and reading without
# explicit synchronization
# (http://www.jython.org/jythonbook/en/1.0/Concurrency.html).
# Please note that in order to make this code safe in a runtime environment
# that does not make this guarantees, it is not sufficient. The
# ThreadLocalProxy must also be created with fallback_to_shared set to
# False or a lock must be added to the ThreadLocalProxy.
if force_lock:
with _inject_into_mod.lock:
if isinstance(old_value, ThreadLocalProxy):
ThreadLocalProxy.set_reference(old_value, value)
else:
setattr(mod, name, ThreadLocalProxy(value, True))
else:
if isinstance(old_value, ThreadLocalProxy):
ThreadLocalProxy.set_reference(old_value, value)
else:
_inject_into_mod(mod, name, value, True) | [
"def",
"_inject_into_mod",
"(",
"mod",
",",
"name",
",",
"value",
",",
"force_lock",
"=",
"False",
")",
":",
"old_value",
"=",
"getattr",
"(",
"mod",
",",
"name",
",",
"None",
")",
"# We use a double-checked locking scheme in order to avoid taking the lock",
"# when... | Inject a variable into a module. This is used to inject "globals" like
``__salt__``, ``__pillar``, or ``grains``.
Instead of injecting the value directly, a ``ThreadLocalProxy`` is created.
If such a proxy is already present under the specified name, it is updated
with the new value. This update only affects the current thread, so that
the same name can refer to different values depending on the thread of
execution.
This is important for data that is not truly global. For example, pillar
data might be dynamically overriden through function parameters and thus
the actual values available in pillar might depend on the thread that is
calling a module.
mod:
module object into which the value is going to be injected.
name:
name of the variable that is injected into the module.
value:
value that is injected into the variable. The value is not injected
directly, but instead set as the new reference of the proxy that has
been created for the variable.
force_lock:
whether the lock should be acquired before checking whether a proxy
object for the specified name has already been injected into the
module. If ``False`` (the default), this function checks for the
module's variable without acquiring the lock and only acquires the lock
if a new proxy has to be created and injected. | [
"Inject",
"a",
"variable",
"into",
"a",
"module",
".",
"This",
"is",
"used",
"to",
"inject",
"globals",
"like",
"__salt__",
"__pillar",
"or",
"grains",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1096-L1155 | train |
saltstack/salt | salt/loader.py | global_injector_decorator | def global_injector_decorator(inject_globals):
'''
Decorator used by the LazyLoader to inject globals into a function at
execute time.
globals
Dictionary with global variables to inject
'''
def inner_decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
with salt.utils.context.func_globals_inject(f, **inject_globals):
return f(*args, **kwargs)
return wrapper
return inner_decorator | python | def global_injector_decorator(inject_globals):
'''
Decorator used by the LazyLoader to inject globals into a function at
execute time.
globals
Dictionary with global variables to inject
'''
def inner_decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
with salt.utils.context.func_globals_inject(f, **inject_globals):
return f(*args, **kwargs)
return wrapper
return inner_decorator | [
"def",
"global_injector_decorator",
"(",
"inject_globals",
")",
":",
"def",
"inner_decorator",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"salt",
"."... | Decorator used by the LazyLoader to inject globals into a function at
execute time.
globals
Dictionary with global variables to inject | [
"Decorator",
"used",
"by",
"the",
"LazyLoader",
"to",
"inject",
"globals",
"into",
"a",
"function",
"at",
"execute",
"time",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L2044-L2058 | train |
saltstack/salt | salt/loader.py | LazyLoader.missing_fun_string | def missing_fun_string(self, function_name):
'''
Return the error string for a missing function.
This can range from "not available' to "__virtual__" returned False
'''
mod_name = function_name.split('.')[0]
if mod_name in self.loaded_modules:
return '\'{0}\' is not available.'.format(function_name)
else:
try:
reason = self.missing_modules[mod_name]
except KeyError:
return '\'{0}\' is not available.'.format(function_name)
else:
if reason is not None:
return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason)
else:
return '\'{0}\' __virtual__ returned False'.format(mod_name) | python | def missing_fun_string(self, function_name):
'''
Return the error string for a missing function.
This can range from "not available' to "__virtual__" returned False
'''
mod_name = function_name.split('.')[0]
if mod_name in self.loaded_modules:
return '\'{0}\' is not available.'.format(function_name)
else:
try:
reason = self.missing_modules[mod_name]
except KeyError:
return '\'{0}\' is not available.'.format(function_name)
else:
if reason is not None:
return '\'{0}\' __virtual__ returned False: {1}'.format(mod_name, reason)
else:
return '\'{0}\' __virtual__ returned False'.format(mod_name) | [
"def",
"missing_fun_string",
"(",
"self",
",",
"function_name",
")",
":",
"mod_name",
"=",
"function_name",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"if",
"mod_name",
"in",
"self",
".",
"loaded_modules",
":",
"return",
"'\\'{0}\\' is not available.'",
"."... | Return the error string for a missing function.
This can range from "not available' to "__virtual__" returned False | [
"Return",
"the",
"error",
"string",
"for",
"a",
"missing",
"function",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1348-L1366 | train |
saltstack/salt | salt/loader.py | LazyLoader._refresh_file_mapping | def _refresh_file_mapping(self):
'''
refresh the mapping of the FS on disk
'''
# map of suffix to description for imp
if self.opts.get('cython_enable', True) is True:
try:
global pyximport
pyximport = __import__('pyximport') # pylint: disable=import-error
pyximport.install()
# add to suffix_map so file_mapping will pick it up
self.suffix_map['.pyx'] = tuple()
except ImportError:
log.info('Cython is enabled in the options but not present '
'in the system path. Skipping Cython modules.')
# Allow for zipimport of modules
if self.opts.get('enable_zip_modules', True) is True:
self.suffix_map['.zip'] = tuple()
# allow for module dirs
if USE_IMPORTLIB:
self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY)
else:
self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY)
# create mapping of filename (without suffix) to (path, suffix)
# The files are added in order of priority, so order *must* be retained.
self.file_mapping = salt.utils.odict.OrderedDict()
opt_match = []
def _replace_pre_ext(obj):
'''
Hack so we can get the optimization level that we replaced (if
any) out of the re.sub call below. We use a list here because
it is a persistent data structure that we will be able to
access after re.sub is called.
'''
opt_match.append(obj)
return ''
for mod_dir in self.module_dirs:
try:
# Make sure we have a sorted listdir in order to have
# expectable override results
files = sorted(
x for x in os.listdir(mod_dir) if x != '__pycache__'
)
except OSError:
continue # Next mod_dir
if six.PY3:
try:
pycache_files = [
os.path.join('__pycache__', x) for x in
sorted(os.listdir(os.path.join(mod_dir, '__pycache__')))
]
except OSError:
pass
else:
files.extend(pycache_files)
for filename in files:
try:
dirname, basename = os.path.split(filename)
if basename.startswith('_'):
# skip private modules
# log messages omitted for obviousness
continue # Next filename
f_noext, ext = os.path.splitext(basename)
if six.PY3:
f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext)
try:
opt_level = int(
opt_match.pop().group(1).rsplit('-', 1)[-1]
)
except (AttributeError, IndexError, ValueError):
# No regex match or no optimization level matched
opt_level = 0
try:
opt_index = self.opts['optimization_order'].index(opt_level)
except KeyError:
log.trace(
'Disallowed optimization level %d for module '
'name \'%s\', skipping. Add %d to the '
'\'optimization_order\' config option if you '
'do not want to ignore this optimization '
'level.', opt_level, f_noext, opt_level
)
continue
else:
# Optimization level not reflected in filename on PY2
opt_index = 0
# make sure it is a suffix we support
if ext not in self.suffix_map:
continue # Next filename
if f_noext in self.disabled:
log.trace(
'Skipping %s, it is disabled by configuration',
filename
)
continue # Next filename
fpath = os.path.join(mod_dir, filename)
# if its a directory, lets allow us to load that
if ext == '':
# is there something __init__?
subfiles = os.listdir(fpath)
for suffix in self.suffix_order:
if '' == suffix:
continue # Next suffix (__init__ must have a suffix)
init_file = '__init__{0}'.format(suffix)
if init_file in subfiles:
break
else:
continue # Next filename
try:
curr_ext = self.file_mapping[f_noext][1]
curr_opt_index = self.file_mapping[f_noext][2]
except KeyError:
pass
else:
if '' in (curr_ext, ext) and curr_ext != ext:
log.error(
'Module/package collision: \'%s\' and \'%s\'',
fpath,
self.file_mapping[f_noext][0]
)
if six.PY3 and ext == '.pyc' and curr_ext == '.pyc':
# Check the optimization level
if opt_index >= curr_opt_index:
# Module name match, but a higher-priority
# optimization level was already matched, skipping.
continue
elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext):
# Match found but a higher-priorty match already
# exists, so skip this.
continue
if six.PY3 and not dirname and ext == '.pyc':
# On Python 3, we should only load .pyc files from the
# __pycache__ subdirectory (i.e. when dirname is not an
# empty string).
continue
# Made it this far - add it
self.file_mapping[f_noext] = (fpath, ext, opt_index)
except OSError:
continue
for smod in self.static_modules:
f_noext = smod.split('.')[-1]
self.file_mapping[f_noext] = (smod, '.o', 0) | python | def _refresh_file_mapping(self):
'''
refresh the mapping of the FS on disk
'''
# map of suffix to description for imp
if self.opts.get('cython_enable', True) is True:
try:
global pyximport
pyximport = __import__('pyximport') # pylint: disable=import-error
pyximport.install()
# add to suffix_map so file_mapping will pick it up
self.suffix_map['.pyx'] = tuple()
except ImportError:
log.info('Cython is enabled in the options but not present '
'in the system path. Skipping Cython modules.')
# Allow for zipimport of modules
if self.opts.get('enable_zip_modules', True) is True:
self.suffix_map['.zip'] = tuple()
# allow for module dirs
if USE_IMPORTLIB:
self.suffix_map[''] = ('', '', MODULE_KIND_PKG_DIRECTORY)
else:
self.suffix_map[''] = ('', '', imp.PKG_DIRECTORY)
# create mapping of filename (without suffix) to (path, suffix)
# The files are added in order of priority, so order *must* be retained.
self.file_mapping = salt.utils.odict.OrderedDict()
opt_match = []
def _replace_pre_ext(obj):
'''
Hack so we can get the optimization level that we replaced (if
any) out of the re.sub call below. We use a list here because
it is a persistent data structure that we will be able to
access after re.sub is called.
'''
opt_match.append(obj)
return ''
for mod_dir in self.module_dirs:
try:
# Make sure we have a sorted listdir in order to have
# expectable override results
files = sorted(
x for x in os.listdir(mod_dir) if x != '__pycache__'
)
except OSError:
continue # Next mod_dir
if six.PY3:
try:
pycache_files = [
os.path.join('__pycache__', x) for x in
sorted(os.listdir(os.path.join(mod_dir, '__pycache__')))
]
except OSError:
pass
else:
files.extend(pycache_files)
for filename in files:
try:
dirname, basename = os.path.split(filename)
if basename.startswith('_'):
# skip private modules
# log messages omitted for obviousness
continue # Next filename
f_noext, ext = os.path.splitext(basename)
if six.PY3:
f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext)
try:
opt_level = int(
opt_match.pop().group(1).rsplit('-', 1)[-1]
)
except (AttributeError, IndexError, ValueError):
# No regex match or no optimization level matched
opt_level = 0
try:
opt_index = self.opts['optimization_order'].index(opt_level)
except KeyError:
log.trace(
'Disallowed optimization level %d for module '
'name \'%s\', skipping. Add %d to the '
'\'optimization_order\' config option if you '
'do not want to ignore this optimization '
'level.', opt_level, f_noext, opt_level
)
continue
else:
# Optimization level not reflected in filename on PY2
opt_index = 0
# make sure it is a suffix we support
if ext not in self.suffix_map:
continue # Next filename
if f_noext in self.disabled:
log.trace(
'Skipping %s, it is disabled by configuration',
filename
)
continue # Next filename
fpath = os.path.join(mod_dir, filename)
# if its a directory, lets allow us to load that
if ext == '':
# is there something __init__?
subfiles = os.listdir(fpath)
for suffix in self.suffix_order:
if '' == suffix:
continue # Next suffix (__init__ must have a suffix)
init_file = '__init__{0}'.format(suffix)
if init_file in subfiles:
break
else:
continue # Next filename
try:
curr_ext = self.file_mapping[f_noext][1]
curr_opt_index = self.file_mapping[f_noext][2]
except KeyError:
pass
else:
if '' in (curr_ext, ext) and curr_ext != ext:
log.error(
'Module/package collision: \'%s\' and \'%s\'',
fpath,
self.file_mapping[f_noext][0]
)
if six.PY3 and ext == '.pyc' and curr_ext == '.pyc':
# Check the optimization level
if opt_index >= curr_opt_index:
# Module name match, but a higher-priority
# optimization level was already matched, skipping.
continue
elif not curr_ext or self.suffix_order.index(ext) >= self.suffix_order.index(curr_ext):
# Match found but a higher-priorty match already
# exists, so skip this.
continue
if six.PY3 and not dirname and ext == '.pyc':
# On Python 3, we should only load .pyc files from the
# __pycache__ subdirectory (i.e. when dirname is not an
# empty string).
continue
# Made it this far - add it
self.file_mapping[f_noext] = (fpath, ext, opt_index)
except OSError:
continue
for smod in self.static_modules:
f_noext = smod.split('.')[-1]
self.file_mapping[f_noext] = (smod, '.o', 0) | [
"def",
"_refresh_file_mapping",
"(",
"self",
")",
":",
"# map of suffix to description for imp",
"if",
"self",
".",
"opts",
".",
"get",
"(",
"'cython_enable'",
",",
"True",
")",
"is",
"True",
":",
"try",
":",
"global",
"pyximport",
"pyximport",
"=",
"__import__"... | refresh the mapping of the FS on disk | [
"refresh",
"the",
"mapping",
"of",
"the",
"FS",
"on",
"disk"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1368-L1520 | train |
saltstack/salt | salt/loader.py | LazyLoader.clear | def clear(self):
'''
Clear the dict
'''
with self._lock:
super(LazyLoader, self).clear() # clear the lazy loader
self.loaded_files = set()
self.missing_modules = {}
self.loaded_modules = {}
# if we have been loaded before, lets clear the file mapping since
# we obviously want a re-do
if hasattr(self, 'opts'):
self._refresh_file_mapping()
self.initial_load = False | python | def clear(self):
'''
Clear the dict
'''
with self._lock:
super(LazyLoader, self).clear() # clear the lazy loader
self.loaded_files = set()
self.missing_modules = {}
self.loaded_modules = {}
# if we have been loaded before, lets clear the file mapping since
# we obviously want a re-do
if hasattr(self, 'opts'):
self._refresh_file_mapping()
self.initial_load = False | [
"def",
"clear",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"super",
"(",
"LazyLoader",
",",
"self",
")",
".",
"clear",
"(",
")",
"# clear the lazy loader",
"self",
".",
"loaded_files",
"=",
"set",
"(",
")",
"self",
".",
"missing_modules",
... | Clear the dict | [
"Clear",
"the",
"dict"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1522-L1535 | train |
saltstack/salt | salt/loader.py | LazyLoader.__prep_mod_opts | def __prep_mod_opts(self, opts):
'''
Strip out of the opts any logger instance
'''
if '__grains__' not in self.pack:
grains = opts.get('grains', {})
if isinstance(grains, ThreadLocalProxy):
grains = ThreadLocalProxy.unproxy(grains)
self.context_dict['grains'] = grains
self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains')
if '__pillar__' not in self.pack:
pillar = opts.get('pillar', {})
if isinstance(pillar, ThreadLocalProxy):
pillar = ThreadLocalProxy.unproxy(pillar)
self.context_dict['pillar'] = pillar
self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar')
mod_opts = {}
for key, val in list(opts.items()):
if key == 'logger':
continue
mod_opts[key] = val
return mod_opts | python | def __prep_mod_opts(self, opts):
'''
Strip out of the opts any logger instance
'''
if '__grains__' not in self.pack:
grains = opts.get('grains', {})
if isinstance(grains, ThreadLocalProxy):
grains = ThreadLocalProxy.unproxy(grains)
self.context_dict['grains'] = grains
self.pack['__grains__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'grains')
if '__pillar__' not in self.pack:
pillar = opts.get('pillar', {})
if isinstance(pillar, ThreadLocalProxy):
pillar = ThreadLocalProxy.unproxy(pillar)
self.context_dict['pillar'] = pillar
self.pack['__pillar__'] = salt.utils.context.NamespacedDictWrapper(self.context_dict, 'pillar')
mod_opts = {}
for key, val in list(opts.items()):
if key == 'logger':
continue
mod_opts[key] = val
return mod_opts | [
"def",
"__prep_mod_opts",
"(",
"self",
",",
"opts",
")",
":",
"if",
"'__grains__'",
"not",
"in",
"self",
".",
"pack",
":",
"grains",
"=",
"opts",
".",
"get",
"(",
"'grains'",
",",
"{",
"}",
")",
"if",
"isinstance",
"(",
"grains",
",",
"ThreadLocalProxy... | Strip out of the opts any logger instance | [
"Strip",
"out",
"of",
"the",
"opts",
"any",
"logger",
"instance"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1537-L1564 | train |
saltstack/salt | salt/loader.py | LazyLoader._iter_files | def _iter_files(self, mod_name):
'''
Iterate over all file_mapping files in order of closeness to mod_name
'''
# do we have an exact match?
if mod_name in self.file_mapping:
yield mod_name
# do we have a partial match?
for k in self.file_mapping:
if mod_name in k:
yield k
# anyone else? Bueller?
for k in self.file_mapping:
if mod_name not in k:
yield k | python | def _iter_files(self, mod_name):
'''
Iterate over all file_mapping files in order of closeness to mod_name
'''
# do we have an exact match?
if mod_name in self.file_mapping:
yield mod_name
# do we have a partial match?
for k in self.file_mapping:
if mod_name in k:
yield k
# anyone else? Bueller?
for k in self.file_mapping:
if mod_name not in k:
yield k | [
"def",
"_iter_files",
"(",
"self",
",",
"mod_name",
")",
":",
"# do we have an exact match?",
"if",
"mod_name",
"in",
"self",
".",
"file_mapping",
":",
"yield",
"mod_name",
"# do we have a partial match?",
"for",
"k",
"in",
"self",
".",
"file_mapping",
":",
"if",
... | Iterate over all file_mapping files in order of closeness to mod_name | [
"Iterate",
"over",
"all",
"file_mapping",
"files",
"in",
"order",
"of",
"closeness",
"to",
"mod_name"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1566-L1582 | train |
saltstack/salt | salt/loader.py | LazyLoader._load | def _load(self, key):
'''
Load a single item if you have it
'''
# if the key doesn't have a '.' then it isn't valid for this mod dict
if not isinstance(key, six.string_types):
raise KeyError('The key must be a string.')
if '.' not in key:
raise KeyError('The key \'{0}\' should contain a \'.\''.format(key))
mod_name, _ = key.split('.', 1)
with self._lock:
# It is possible that the key is in the dictionary after
# acquiring the lock due to another thread loading it.
if mod_name in self.missing_modules or key in self._dict:
return True
# if the modulename isn't in the whitelist, don't bother
if self.whitelist and mod_name not in self.whitelist:
log.error(
'Failed to load function %s because its module (%s) is '
'not in the whitelist: %s', key, mod_name, self.whitelist
)
raise KeyError(key)
def _inner_load(mod_name):
for name in self._iter_files(mod_name):
if name in self.loaded_files:
continue
# if we got what we wanted, we are done
if self._load_module(name) and key in self._dict:
return True
return False
# try to load the module
ret = None
reloaded = False
# re-scan up to once, IOErrors or a failed load cause re-scans of the
# filesystem
while True:
try:
ret = _inner_load(mod_name)
if not reloaded and ret is not True:
self._refresh_file_mapping()
reloaded = True
continue
break
except IOError:
if not reloaded:
self._refresh_file_mapping()
reloaded = True
continue
return ret | python | def _load(self, key):
'''
Load a single item if you have it
'''
# if the key doesn't have a '.' then it isn't valid for this mod dict
if not isinstance(key, six.string_types):
raise KeyError('The key must be a string.')
if '.' not in key:
raise KeyError('The key \'{0}\' should contain a \'.\''.format(key))
mod_name, _ = key.split('.', 1)
with self._lock:
# It is possible that the key is in the dictionary after
# acquiring the lock due to another thread loading it.
if mod_name in self.missing_modules or key in self._dict:
return True
# if the modulename isn't in the whitelist, don't bother
if self.whitelist and mod_name not in self.whitelist:
log.error(
'Failed to load function %s because its module (%s) is '
'not in the whitelist: %s', key, mod_name, self.whitelist
)
raise KeyError(key)
def _inner_load(mod_name):
for name in self._iter_files(mod_name):
if name in self.loaded_files:
continue
# if we got what we wanted, we are done
if self._load_module(name) and key in self._dict:
return True
return False
# try to load the module
ret = None
reloaded = False
# re-scan up to once, IOErrors or a failed load cause re-scans of the
# filesystem
while True:
try:
ret = _inner_load(mod_name)
if not reloaded and ret is not True:
self._refresh_file_mapping()
reloaded = True
continue
break
except IOError:
if not reloaded:
self._refresh_file_mapping()
reloaded = True
continue
return ret | [
"def",
"_load",
"(",
"self",
",",
"key",
")",
":",
"# if the key doesn't have a '.' then it isn't valid for this mod dict",
"if",
"not",
"isinstance",
"(",
"key",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"KeyError",
"(",
"'The key must be a string.'",
")",
... | Load a single item if you have it | [
"Load",
"a",
"single",
"item",
"if",
"you",
"have",
"it"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1851-L1902 | train |
saltstack/salt | salt/loader.py | LazyLoader._load_all | def _load_all(self):
'''
Load all of them
'''
with self._lock:
for name in self.file_mapping:
if name in self.loaded_files or name in self.missing_modules:
continue
self._load_module(name)
self.loaded = True | python | def _load_all(self):
'''
Load all of them
'''
with self._lock:
for name in self.file_mapping:
if name in self.loaded_files or name in self.missing_modules:
continue
self._load_module(name)
self.loaded = True | [
"def",
"_load_all",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"for",
"name",
"in",
"self",
".",
"file_mapping",
":",
"if",
"name",
"in",
"self",
".",
"loaded_files",
"or",
"name",
"in",
"self",
".",
"missing_modules",
":",
"continue",
"... | Load all of them | [
"Load",
"all",
"of",
"them"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1904-L1914 | train |
saltstack/salt | salt/loader.py | LazyLoader._apply_outputter | def _apply_outputter(self, func, mod):
'''
Apply the __outputter__ variable to the functions
'''
if hasattr(mod, '__outputter__'):
outp = mod.__outputter__
if func.__name__ in outp:
func.__outputter__ = outp[func.__name__] | python | def _apply_outputter(self, func, mod):
'''
Apply the __outputter__ variable to the functions
'''
if hasattr(mod, '__outputter__'):
outp = mod.__outputter__
if func.__name__ in outp:
func.__outputter__ = outp[func.__name__] | [
"def",
"_apply_outputter",
"(",
"self",
",",
"func",
",",
"mod",
")",
":",
"if",
"hasattr",
"(",
"mod",
",",
"'__outputter__'",
")",
":",
"outp",
"=",
"mod",
".",
"__outputter__",
"if",
"func",
".",
"__name__",
"in",
"outp",
":",
"func",
".",
"__output... | Apply the __outputter__ variable to the functions | [
"Apply",
"the",
"__outputter__",
"variable",
"to",
"the",
"functions"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1921-L1928 | train |
saltstack/salt | salt/loader.py | LazyLoader._process_virtual | def _process_virtual(self, mod, module_name, virtual_func='__virtual__'):
'''
Given a loaded module and its default name determine its virtual name
This function returns a tuple. The first value will be either True or
False and will indicate if the module should be loaded or not (i.e. if
it threw and exception while processing its __virtual__ function). The
second value is the determined virtual name, which may be the same as
the value provided.
The default name can be calculated as follows::
module_name = mod.__name__.rsplit('.', 1)[-1]
'''
# The __virtual__ function will return either a True or False value.
# If it returns a True value it can also set a module level attribute
# named __virtualname__ with the name that the module should be
# referred to as.
#
# This allows us to have things like the pkg module working on all
# platforms under the name 'pkg'. It also allows for modules like
# augeas_cfg to be referred to as 'augeas', which would otherwise have
# namespace collisions. And finally it allows modules to return False
# if they are not intended to run on the given platform or are missing
# dependencies.
virtual_aliases = getattr(mod, '__virtual_aliases__', tuple())
try:
error_reason = None
if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__):
try:
start = time.time()
virtual = getattr(mod, virtual_func)()
if isinstance(virtual, tuple):
error_reason = virtual[1]
virtual = virtual[0]
if self.opts.get('virtual_timer', False):
end = time.time() - start
msg = 'Virtual function took {0} seconds for {1}'.format(
end, module_name)
log.warning(msg)
except Exception as exc:
error_reason = (
'Exception raised when processing __virtual__ function'
' for {0}. Module will not be loaded: {1}'.format(
mod.__name__, exc))
log.error(error_reason, exc_info_on_loglevel=logging.DEBUG)
virtual = None
# Get the module's virtual name
virtualname = getattr(mod, '__virtualname__', virtual)
if not virtual:
# if __virtual__() evaluates to False then the module
# wasn't meant for this platform or it's not supposed to
# load for some other reason.
# Some modules might accidentally return None and are
# improperly loaded
if virtual is None:
log.warning(
'%s.__virtual__() is wrongly returning `None`. '
'It should either return `True`, `False` or a new '
'name. If you\'re the developer of the module '
'\'%s\', please fix this.', mod.__name__, module_name
)
return (False, module_name, error_reason, virtual_aliases)
# At this point, __virtual__ did not return a
# boolean value, let's check for deprecated usage
# or module renames
if virtual is not True and module_name != virtual:
# The module is renaming itself. Updating the module name
# with the new name
log.trace('Loaded %s as virtual %s', module_name, virtual)
if virtualname != virtual:
# The __virtualname__ attribute does not match what's
# being returned by the __virtual__() function. This
# should be considered an error.
log.error(
'The module \'%s\' is showing some bad usage. Its '
'__virtualname__ attribute is set to \'%s\' yet the '
'__virtual__() function is returning \'%s\'. These '
'values should match!',
mod.__name__, virtualname, virtual
)
module_name = virtualname
# If the __virtual__ function returns True and __virtualname__
# is set then use it
elif virtual is True and virtualname != module_name:
if virtualname is not True:
module_name = virtualname
except KeyError:
# Key errors come out of the virtual function when passing
# in incomplete grains sets, these can be safely ignored
# and logged to debug, still, it includes the traceback to
# help debugging.
log.debug('KeyError when loading %s', module_name, exc_info=True)
except Exception:
# If the module throws an exception during __virtual__()
# then log the information and continue to the next.
log.error(
'Failed to read the virtual function for %s: %s',
self.tag, module_name, exc_info=True
)
return (False, module_name, error_reason, virtual_aliases)
return (True, module_name, None, virtual_aliases) | python | def _process_virtual(self, mod, module_name, virtual_func='__virtual__'):
'''
Given a loaded module and its default name determine its virtual name
This function returns a tuple. The first value will be either True or
False and will indicate if the module should be loaded or not (i.e. if
it threw and exception while processing its __virtual__ function). The
second value is the determined virtual name, which may be the same as
the value provided.
The default name can be calculated as follows::
module_name = mod.__name__.rsplit('.', 1)[-1]
'''
# The __virtual__ function will return either a True or False value.
# If it returns a True value it can also set a module level attribute
# named __virtualname__ with the name that the module should be
# referred to as.
#
# This allows us to have things like the pkg module working on all
# platforms under the name 'pkg'. It also allows for modules like
# augeas_cfg to be referred to as 'augeas', which would otherwise have
# namespace collisions. And finally it allows modules to return False
# if they are not intended to run on the given platform or are missing
# dependencies.
virtual_aliases = getattr(mod, '__virtual_aliases__', tuple())
try:
error_reason = None
if hasattr(mod, '__virtual__') and inspect.isfunction(mod.__virtual__):
try:
start = time.time()
virtual = getattr(mod, virtual_func)()
if isinstance(virtual, tuple):
error_reason = virtual[1]
virtual = virtual[0]
if self.opts.get('virtual_timer', False):
end = time.time() - start
msg = 'Virtual function took {0} seconds for {1}'.format(
end, module_name)
log.warning(msg)
except Exception as exc:
error_reason = (
'Exception raised when processing __virtual__ function'
' for {0}. Module will not be loaded: {1}'.format(
mod.__name__, exc))
log.error(error_reason, exc_info_on_loglevel=logging.DEBUG)
virtual = None
# Get the module's virtual name
virtualname = getattr(mod, '__virtualname__', virtual)
if not virtual:
# if __virtual__() evaluates to False then the module
# wasn't meant for this platform or it's not supposed to
# load for some other reason.
# Some modules might accidentally return None and are
# improperly loaded
if virtual is None:
log.warning(
'%s.__virtual__() is wrongly returning `None`. '
'It should either return `True`, `False` or a new '
'name. If you\'re the developer of the module '
'\'%s\', please fix this.', mod.__name__, module_name
)
return (False, module_name, error_reason, virtual_aliases)
# At this point, __virtual__ did not return a
# boolean value, let's check for deprecated usage
# or module renames
if virtual is not True and module_name != virtual:
# The module is renaming itself. Updating the module name
# with the new name
log.trace('Loaded %s as virtual %s', module_name, virtual)
if virtualname != virtual:
# The __virtualname__ attribute does not match what's
# being returned by the __virtual__() function. This
# should be considered an error.
log.error(
'The module \'%s\' is showing some bad usage. Its '
'__virtualname__ attribute is set to \'%s\' yet the '
'__virtual__() function is returning \'%s\'. These '
'values should match!',
mod.__name__, virtualname, virtual
)
module_name = virtualname
# If the __virtual__ function returns True and __virtualname__
# is set then use it
elif virtual is True and virtualname != module_name:
if virtualname is not True:
module_name = virtualname
except KeyError:
# Key errors come out of the virtual function when passing
# in incomplete grains sets, these can be safely ignored
# and logged to debug, still, it includes the traceback to
# help debugging.
log.debug('KeyError when loading %s', module_name, exc_info=True)
except Exception:
# If the module throws an exception during __virtual__()
# then log the information and continue to the next.
log.error(
'Failed to read the virtual function for %s: %s',
self.tag, module_name, exc_info=True
)
return (False, module_name, error_reason, virtual_aliases)
return (True, module_name, None, virtual_aliases) | [
"def",
"_process_virtual",
"(",
"self",
",",
"mod",
",",
"module_name",
",",
"virtual_func",
"=",
"'__virtual__'",
")",
":",
"# The __virtual__ function will return either a True or False value.",
"# If it returns a True value it can also set a module level attribute",
"# named __vir... | Given a loaded module and its default name determine its virtual name
This function returns a tuple. The first value will be either True or
False and will indicate if the module should be loaded or not (i.e. if
it threw and exception while processing its __virtual__ function). The
second value is the determined virtual name, which may be the same as
the value provided.
The default name can be calculated as follows::
module_name = mod.__name__.rsplit('.', 1)[-1] | [
"Given",
"a",
"loaded",
"module",
"and",
"its",
"default",
"name",
"determine",
"its",
"virtual",
"name"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/loader.py#L1930-L2041 | train |
saltstack/salt | salt/modules/smbios.py | get | def get(string, clean=True):
'''
Get an individual DMI string from SMBIOS info
string
The string to fetch. DMIdecode supports:
- ``bios-vendor``
- ``bios-version``
- ``bios-release-date``
- ``system-manufacturer``
- ``system-product-name``
- ``system-version``
- ``system-serial-number``
- ``system-uuid``
- ``baseboard-manufacturer``
- ``baseboard-product-name``
- ``baseboard-version``
- ``baseboard-serial-number``
- ``baseboard-asset-tag``
- ``chassis-manufacturer``
- ``chassis-type``
- ``chassis-version``
- ``chassis-serial-number``
- ``chassis-asset-tag``
- ``processor-family``
- ``processor-manufacturer``
- ``processor-version``
- ``processor-frequency``
clean
| Don't return well-known false information
| (invalid UUID's, serial 000000000's, etcetera)
| Defaults to ``True``
CLI Example:
.. code-block:: bash
salt '*' smbios.get system-uuid clean=False
'''
val = _dmidecoder('-s {0}'.format(string)).strip()
# Cleanup possible comments in strings.
val = '\n'.join([v for v in val.split('\n') if not v.startswith('#')])
if val.startswith('/dev/mem') or clean and not _dmi_isclean(string, val):
val = None
return val | python | def get(string, clean=True):
'''
Get an individual DMI string from SMBIOS info
string
The string to fetch. DMIdecode supports:
- ``bios-vendor``
- ``bios-version``
- ``bios-release-date``
- ``system-manufacturer``
- ``system-product-name``
- ``system-version``
- ``system-serial-number``
- ``system-uuid``
- ``baseboard-manufacturer``
- ``baseboard-product-name``
- ``baseboard-version``
- ``baseboard-serial-number``
- ``baseboard-asset-tag``
- ``chassis-manufacturer``
- ``chassis-type``
- ``chassis-version``
- ``chassis-serial-number``
- ``chassis-asset-tag``
- ``processor-family``
- ``processor-manufacturer``
- ``processor-version``
- ``processor-frequency``
clean
| Don't return well-known false information
| (invalid UUID's, serial 000000000's, etcetera)
| Defaults to ``True``
CLI Example:
.. code-block:: bash
salt '*' smbios.get system-uuid clean=False
'''
val = _dmidecoder('-s {0}'.format(string)).strip()
# Cleanup possible comments in strings.
val = '\n'.join([v for v in val.split('\n') if not v.startswith('#')])
if val.startswith('/dev/mem') or clean and not _dmi_isclean(string, val):
val = None
return val | [
"def",
"get",
"(",
"string",
",",
"clean",
"=",
"True",
")",
":",
"val",
"=",
"_dmidecoder",
"(",
"'-s {0}'",
".",
"format",
"(",
"string",
")",
")",
".",
"strip",
"(",
")",
"# Cleanup possible comments in strings.",
"val",
"=",
"'\\n'",
".",
"join",
"("... | Get an individual DMI string from SMBIOS info
string
The string to fetch. DMIdecode supports:
- ``bios-vendor``
- ``bios-version``
- ``bios-release-date``
- ``system-manufacturer``
- ``system-product-name``
- ``system-version``
- ``system-serial-number``
- ``system-uuid``
- ``baseboard-manufacturer``
- ``baseboard-product-name``
- ``baseboard-version``
- ``baseboard-serial-number``
- ``baseboard-asset-tag``
- ``chassis-manufacturer``
- ``chassis-type``
- ``chassis-version``
- ``chassis-serial-number``
- ``chassis-asset-tag``
- ``processor-family``
- ``processor-manufacturer``
- ``processor-version``
- ``processor-frequency``
clean
| Don't return well-known false information
| (invalid UUID's, serial 000000000's, etcetera)
| Defaults to ``True``
CLI Example:
.. code-block:: bash
salt '*' smbios.get system-uuid clean=False | [
"Get",
"an",
"individual",
"DMI",
"string",
"from",
"SMBIOS",
"info"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smbios.py#L41-L89 | train |
saltstack/salt | salt/modules/smbios.py | records | def records(rec_type=None, fields=None, clean=True):
'''
Return DMI records from SMBIOS
type
Return only records of type(s)
The SMBIOS specification defines the following DMI types:
==== ======================================
Type Information
==== ======================================
0 BIOS
1 System
2 Baseboard
3 Chassis
4 Processor
5 Memory Controller
6 Memory Module
7 Cache
8 Port Connector
9 System Slots
10 On Board Devices
11 OEM Strings
12 System Configuration Options
13 BIOS Language
14 Group Associations
15 System Event Log
16 Physical Memory Array
17 Memory Device
18 32-bit Memory Error
19 Memory Array Mapped Address
20 Memory Device Mapped Address
21 Built-in Pointing Device
22 Portable Battery
23 System Reset
24 Hardware Security
25 System Power Controls
26 Voltage Probe
27 Cooling Device
28 Temperature Probe
29 Electrical Current Probe
30 Out-of-band Remote Access
31 Boot Integrity Services
32 System Boot
33 64-bit Memory Error
34 Management Device
35 Management Device Component
36 Management Device Threshold Data
37 Memory Channel
38 IPMI Device
39 Power Supply
40 Additional Information
41 Onboard Devices Extended Information
42 Management Controller Host Interface
==== ======================================
clean
| Don't return well-known false information
| (invalid UUID's, serial 000000000's, etcetera)
| Defaults to ``True``
CLI Example:
.. code-block:: bash
salt '*' smbios.records clean=False
salt '*' smbios.records 14
salt '*' smbios.records 4 core_count,thread_count,current_speed
'''
if rec_type is None:
smbios = _dmi_parse(_dmidecoder(), clean, fields)
else:
smbios = _dmi_parse(_dmidecoder('-t {0}'.format(rec_type)), clean, fields)
return smbios | python | def records(rec_type=None, fields=None, clean=True):
'''
Return DMI records from SMBIOS
type
Return only records of type(s)
The SMBIOS specification defines the following DMI types:
==== ======================================
Type Information
==== ======================================
0 BIOS
1 System
2 Baseboard
3 Chassis
4 Processor
5 Memory Controller
6 Memory Module
7 Cache
8 Port Connector
9 System Slots
10 On Board Devices
11 OEM Strings
12 System Configuration Options
13 BIOS Language
14 Group Associations
15 System Event Log
16 Physical Memory Array
17 Memory Device
18 32-bit Memory Error
19 Memory Array Mapped Address
20 Memory Device Mapped Address
21 Built-in Pointing Device
22 Portable Battery
23 System Reset
24 Hardware Security
25 System Power Controls
26 Voltage Probe
27 Cooling Device
28 Temperature Probe
29 Electrical Current Probe
30 Out-of-band Remote Access
31 Boot Integrity Services
32 System Boot
33 64-bit Memory Error
34 Management Device
35 Management Device Component
36 Management Device Threshold Data
37 Memory Channel
38 IPMI Device
39 Power Supply
40 Additional Information
41 Onboard Devices Extended Information
42 Management Controller Host Interface
==== ======================================
clean
| Don't return well-known false information
| (invalid UUID's, serial 000000000's, etcetera)
| Defaults to ``True``
CLI Example:
.. code-block:: bash
salt '*' smbios.records clean=False
salt '*' smbios.records 14
salt '*' smbios.records 4 core_count,thread_count,current_speed
'''
if rec_type is None:
smbios = _dmi_parse(_dmidecoder(), clean, fields)
else:
smbios = _dmi_parse(_dmidecoder('-t {0}'.format(rec_type)), clean, fields)
return smbios | [
"def",
"records",
"(",
"rec_type",
"=",
"None",
",",
"fields",
"=",
"None",
",",
"clean",
"=",
"True",
")",
":",
"if",
"rec_type",
"is",
"None",
":",
"smbios",
"=",
"_dmi_parse",
"(",
"_dmidecoder",
"(",
")",
",",
"clean",
",",
"fields",
")",
"else",... | Return DMI records from SMBIOS
type
Return only records of type(s)
The SMBIOS specification defines the following DMI types:
==== ======================================
Type Information
==== ======================================
0 BIOS
1 System
2 Baseboard
3 Chassis
4 Processor
5 Memory Controller
6 Memory Module
7 Cache
8 Port Connector
9 System Slots
10 On Board Devices
11 OEM Strings
12 System Configuration Options
13 BIOS Language
14 Group Associations
15 System Event Log
16 Physical Memory Array
17 Memory Device
18 32-bit Memory Error
19 Memory Array Mapped Address
20 Memory Device Mapped Address
21 Built-in Pointing Device
22 Portable Battery
23 System Reset
24 Hardware Security
25 System Power Controls
26 Voltage Probe
27 Cooling Device
28 Temperature Probe
29 Electrical Current Probe
30 Out-of-band Remote Access
31 Boot Integrity Services
32 System Boot
33 64-bit Memory Error
34 Management Device
35 Management Device Component
36 Management Device Threshold Data
37 Memory Channel
38 IPMI Device
39 Power Supply
40 Additional Information
41 Onboard Devices Extended Information
42 Management Controller Host Interface
==== ======================================
clean
| Don't return well-known false information
| (invalid UUID's, serial 000000000's, etcetera)
| Defaults to ``True``
CLI Example:
.. code-block:: bash
salt '*' smbios.records clean=False
salt '*' smbios.records 14
salt '*' smbios.records 4 core_count,thread_count,current_speed | [
"Return",
"DMI",
"records",
"from",
"SMBIOS"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smbios.py#L92-L167 | train |
saltstack/salt | salt/modules/smbios.py | _dmi_parse | def _dmi_parse(data, clean=True, fields=None):
'''
Structurize DMI records into a nice list
Optionally trash bogus entries and filter output
'''
dmi = []
# Detect & split Handle records
dmi_split = re.compile('(handle [0-9]x[0-9a-f]+[^\n]+)\n', re.MULTILINE+re.IGNORECASE)
dmi_raw = iter(re.split(dmi_split, data)[1:])
for handle, dmi_raw in zip(dmi_raw, dmi_raw):
handle, htype = [hline.split()[-1] for hline in handle.split(',')][0:2]
dmi_raw = dmi_raw.split('\n')
# log.debug('%s record contains %s', handle, dmi_raw)
log.debug('Parsing handle %s', handle)
# The first line of a handle is a description of the type
record = {
'handle': handle,
'description': dmi_raw.pop(0).strip(),
'type': int(htype)
}
if not dmi_raw:
# empty record
if not clean:
dmi.append(record)
continue
# log.debug('%s record contains %s', record, dmi_raw)
dmi_data = _dmi_data(dmi_raw, clean, fields)
if dmi_data:
record['data'] = dmi_data
dmi.append(record)
elif not clean:
dmi.append(record)
return dmi | python | def _dmi_parse(data, clean=True, fields=None):
'''
Structurize DMI records into a nice list
Optionally trash bogus entries and filter output
'''
dmi = []
# Detect & split Handle records
dmi_split = re.compile('(handle [0-9]x[0-9a-f]+[^\n]+)\n', re.MULTILINE+re.IGNORECASE)
dmi_raw = iter(re.split(dmi_split, data)[1:])
for handle, dmi_raw in zip(dmi_raw, dmi_raw):
handle, htype = [hline.split()[-1] for hline in handle.split(',')][0:2]
dmi_raw = dmi_raw.split('\n')
# log.debug('%s record contains %s', handle, dmi_raw)
log.debug('Parsing handle %s', handle)
# The first line of a handle is a description of the type
record = {
'handle': handle,
'description': dmi_raw.pop(0).strip(),
'type': int(htype)
}
if not dmi_raw:
# empty record
if not clean:
dmi.append(record)
continue
# log.debug('%s record contains %s', record, dmi_raw)
dmi_data = _dmi_data(dmi_raw, clean, fields)
if dmi_data:
record['data'] = dmi_data
dmi.append(record)
elif not clean:
dmi.append(record)
return dmi | [
"def",
"_dmi_parse",
"(",
"data",
",",
"clean",
"=",
"True",
",",
"fields",
"=",
"None",
")",
":",
"dmi",
"=",
"[",
"]",
"# Detect & split Handle records",
"dmi_split",
"=",
"re",
".",
"compile",
"(",
"'(handle [0-9]x[0-9a-f]+[^\\n]+)\\n'",
",",
"re",
".",
"... | Structurize DMI records into a nice list
Optionally trash bogus entries and filter output | [
"Structurize",
"DMI",
"records",
"into",
"a",
"nice",
"list",
"Optionally",
"trash",
"bogus",
"entries",
"and",
"filter",
"output"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smbios.py#L170-L207 | train |
saltstack/salt | salt/modules/smbios.py | _dmi_data | def _dmi_data(dmi_raw, clean, fields):
'''
Parse the raw DMIdecode output of a single handle
into a nice dict
'''
dmi_data = {}
key = None
key_data = [None, []]
for line in dmi_raw:
if re.match(r'\t[^\s]+', line):
# Finish previous key
if key is not None:
# log.debug('Evaluating DMI key {0}: {1}'.format(key, key_data))
value, vlist = key_data
if vlist:
if value is not None:
# On the rare occasion
# (I counted 1 on all systems we have)
# that there's both a value <and> a list
# just insert the value on top of the list
vlist.insert(0, value)
dmi_data[key] = vlist
elif value is not None:
dmi_data[key] = value
# Family: Core i5
# Keyboard Password Status: Not Implemented
key, val = line.split(':', 1)
key = key.strip().lower().replace(' ', '_')
if (clean and key == 'header_and_data') \
or (fields and key not in fields):
key = None
continue
else:
key_data = [_dmi_cast(key, val.strip(), clean), []]
elif key is None:
continue
elif re.match(r'\t\t[^\s]+', line):
# Installable Languages: 1
# en-US
# Characteristics:
# PCI is supported
# PNP is supported
val = _dmi_cast(key, line.strip(), clean)
if val is not None:
# log.debug('DMI key %s gained list item %s', key, val)
key_data[1].append(val)
return dmi_data | python | def _dmi_data(dmi_raw, clean, fields):
'''
Parse the raw DMIdecode output of a single handle
into a nice dict
'''
dmi_data = {}
key = None
key_data = [None, []]
for line in dmi_raw:
if re.match(r'\t[^\s]+', line):
# Finish previous key
if key is not None:
# log.debug('Evaluating DMI key {0}: {1}'.format(key, key_data))
value, vlist = key_data
if vlist:
if value is not None:
# On the rare occasion
# (I counted 1 on all systems we have)
# that there's both a value <and> a list
# just insert the value on top of the list
vlist.insert(0, value)
dmi_data[key] = vlist
elif value is not None:
dmi_data[key] = value
# Family: Core i5
# Keyboard Password Status: Not Implemented
key, val = line.split(':', 1)
key = key.strip().lower().replace(' ', '_')
if (clean and key == 'header_and_data') \
or (fields and key not in fields):
key = None
continue
else:
key_data = [_dmi_cast(key, val.strip(), clean), []]
elif key is None:
continue
elif re.match(r'\t\t[^\s]+', line):
# Installable Languages: 1
# en-US
# Characteristics:
# PCI is supported
# PNP is supported
val = _dmi_cast(key, line.strip(), clean)
if val is not None:
# log.debug('DMI key %s gained list item %s', key, val)
key_data[1].append(val)
return dmi_data | [
"def",
"_dmi_data",
"(",
"dmi_raw",
",",
"clean",
",",
"fields",
")",
":",
"dmi_data",
"=",
"{",
"}",
"key",
"=",
"None",
"key_data",
"=",
"[",
"None",
",",
"[",
"]",
"]",
"for",
"line",
"in",
"dmi_raw",
":",
"if",
"re",
".",
"match",
"(",
"r'\\t... | Parse the raw DMIdecode output of a single handle
into a nice dict | [
"Parse",
"the",
"raw",
"DMIdecode",
"output",
"of",
"a",
"single",
"handle",
"into",
"a",
"nice",
"dict"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smbios.py#L210-L259 | train |
saltstack/salt | salt/modules/smbios.py | _dmi_cast | def _dmi_cast(key, val, clean=True):
'''
Simple caster thingy for trying to fish out at least ints & lists from strings
'''
if clean and not _dmi_isclean(key, val):
return
elif not re.match(r'serial|part|asset|product', key, flags=re.IGNORECASE):
if ',' in val:
val = [el.strip() for el in val.split(',')]
else:
try:
val = int(val)
except Exception:
pass
return val | python | def _dmi_cast(key, val, clean=True):
'''
Simple caster thingy for trying to fish out at least ints & lists from strings
'''
if clean and not _dmi_isclean(key, val):
return
elif not re.match(r'serial|part|asset|product', key, flags=re.IGNORECASE):
if ',' in val:
val = [el.strip() for el in val.split(',')]
else:
try:
val = int(val)
except Exception:
pass
return val | [
"def",
"_dmi_cast",
"(",
"key",
",",
"val",
",",
"clean",
"=",
"True",
")",
":",
"if",
"clean",
"and",
"not",
"_dmi_isclean",
"(",
"key",
",",
"val",
")",
":",
"return",
"elif",
"not",
"re",
".",
"match",
"(",
"r'serial|part|asset|product'",
",",
"key"... | Simple caster thingy for trying to fish out at least ints & lists from strings | [
"Simple",
"caster",
"thingy",
"for",
"trying",
"to",
"fish",
"out",
"at",
"least",
"ints",
"&",
"lists",
"from",
"strings"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smbios.py#L262-L277 | train |
saltstack/salt | salt/modules/smbios.py | _dmidecoder | def _dmidecoder(args=None):
'''
Call DMIdecode
'''
dmidecoder = salt.utils.path.which_bin(['dmidecode', 'smbios'])
if not args:
out = salt.modules.cmdmod._run_quiet(dmidecoder)
else:
out = salt.modules.cmdmod._run_quiet('{0} {1}'.format(dmidecoder, args))
return out | python | def _dmidecoder(args=None):
'''
Call DMIdecode
'''
dmidecoder = salt.utils.path.which_bin(['dmidecode', 'smbios'])
if not args:
out = salt.modules.cmdmod._run_quiet(dmidecoder)
else:
out = salt.modules.cmdmod._run_quiet('{0} {1}'.format(dmidecoder, args))
return out | [
"def",
"_dmidecoder",
"(",
"args",
"=",
"None",
")",
":",
"dmidecoder",
"=",
"salt",
".",
"utils",
".",
"path",
".",
"which_bin",
"(",
"[",
"'dmidecode'",
",",
"'smbios'",
"]",
")",
"if",
"not",
"args",
":",
"out",
"=",
"salt",
".",
"modules",
".",
... | Call DMIdecode | [
"Call",
"DMIdecode"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/smbios.py#L316-L327 | train |
saltstack/salt | salt/utils/yamlloader.py | SaltYamlSafeLoader.construct_mapping | def construct_mapping(self, node, deep=False):
'''
Build the mapping for YAML
'''
if not isinstance(node, MappingNode):
raise ConstructorError(
None,
None,
'expected a mapping node, but found {0}'.format(node.id),
node.start_mark)
self.flatten_mapping(node)
context = 'while constructing a mapping'
mapping = self.dictclass()
for key_node, value_node in node.value:
key = self.construct_object(key_node, deep=deep)
try:
hash(key)
except TypeError:
raise ConstructorError(
context,
node.start_mark,
"found unacceptable key {0}".format(key_node.value),
key_node.start_mark)
value = self.construct_object(value_node, deep=deep)
if key in mapping:
raise ConstructorError(
context,
node.start_mark,
"found conflicting ID '{0}'".format(key),
key_node.start_mark)
mapping[key] = value
return mapping | python | def construct_mapping(self, node, deep=False):
'''
Build the mapping for YAML
'''
if not isinstance(node, MappingNode):
raise ConstructorError(
None,
None,
'expected a mapping node, but found {0}'.format(node.id),
node.start_mark)
self.flatten_mapping(node)
context = 'while constructing a mapping'
mapping = self.dictclass()
for key_node, value_node in node.value:
key = self.construct_object(key_node, deep=deep)
try:
hash(key)
except TypeError:
raise ConstructorError(
context,
node.start_mark,
"found unacceptable key {0}".format(key_node.value),
key_node.start_mark)
value = self.construct_object(value_node, deep=deep)
if key in mapping:
raise ConstructorError(
context,
node.start_mark,
"found conflicting ID '{0}'".format(key),
key_node.start_mark)
mapping[key] = value
return mapping | [
"def",
"construct_mapping",
"(",
"self",
",",
"node",
",",
"deep",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"MappingNode",
")",
":",
"raise",
"ConstructorError",
"(",
"None",
",",
"None",
",",
"'expected a mapping node, but found {0... | Build the mapping for YAML | [
"Build",
"the",
"mapping",
"for",
"YAML"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/yamlloader.py#L72-L105 | train |
saltstack/salt | salt/utils/yamlloader.py | SaltYamlSafeLoader.construct_scalar | def construct_scalar(self, node):
'''
Verify integers and pass them in correctly is they are declared
as octal
'''
if node.tag == 'tag:yaml.org,2002:int':
if node.value == '0':
pass
elif node.value.startswith('0') and not node.value.startswith(('0b', '0x')):
node.value = node.value.lstrip('0')
# If value was all zeros, node.value would have been reduced to
# an empty string. Change it to '0'.
if node.value == '':
node.value = '0'
return super(SaltYamlSafeLoader, self).construct_scalar(node) | python | def construct_scalar(self, node):
'''
Verify integers and pass them in correctly is they are declared
as octal
'''
if node.tag == 'tag:yaml.org,2002:int':
if node.value == '0':
pass
elif node.value.startswith('0') and not node.value.startswith(('0b', '0x')):
node.value = node.value.lstrip('0')
# If value was all zeros, node.value would have been reduced to
# an empty string. Change it to '0'.
if node.value == '':
node.value = '0'
return super(SaltYamlSafeLoader, self).construct_scalar(node) | [
"def",
"construct_scalar",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
".",
"tag",
"==",
"'tag:yaml.org,2002:int'",
":",
"if",
"node",
".",
"value",
"==",
"'0'",
":",
"pass",
"elif",
"node",
".",
"value",
".",
"startswith",
"(",
"'0'",
")",
"and"... | Verify integers and pass them in correctly is they are declared
as octal | [
"Verify",
"integers",
"and",
"pass",
"them",
"in",
"correctly",
"is",
"they",
"are",
"declared",
"as",
"octal"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/yamlloader.py#L107-L121 | train |
saltstack/salt | salt/ext/ipaddress.py | ip_address | def ip_address(address):
"""Take an IP string/int and return an object of the correct type.
Args:
address: A string or integer, the IP address. Either IPv4 or
IPv6 addresses may be supplied; integers less than 2**32 will
be considered to be IPv4 by default.
Returns:
An IPv4Address or IPv6Address object.
Raises:
ValueError: if the *address* passed isn't either a v4 or a v6
address
"""
try:
return IPv4Address(address)
except (AddressValueError, NetmaskValueError):
pass
try:
return IPv6Address(address)
except (AddressValueError, NetmaskValueError):
pass
raise ValueError('%r does not appear to be an IPv4 or IPv6 address' %
address) | python | def ip_address(address):
"""Take an IP string/int and return an object of the correct type.
Args:
address: A string or integer, the IP address. Either IPv4 or
IPv6 addresses may be supplied; integers less than 2**32 will
be considered to be IPv4 by default.
Returns:
An IPv4Address or IPv6Address object.
Raises:
ValueError: if the *address* passed isn't either a v4 or a v6
address
"""
try:
return IPv4Address(address)
except (AddressValueError, NetmaskValueError):
pass
try:
return IPv6Address(address)
except (AddressValueError, NetmaskValueError):
pass
raise ValueError('%r does not appear to be an IPv4 or IPv6 address' %
address) | [
"def",
"ip_address",
"(",
"address",
")",
":",
"try",
":",
"return",
"IPv4Address",
"(",
"address",
")",
"except",
"(",
"AddressValueError",
",",
"NetmaskValueError",
")",
":",
"pass",
"try",
":",
"return",
"IPv6Address",
"(",
"address",
")",
"except",
"(",
... | Take an IP string/int and return an object of the correct type.
Args:
address: A string or integer, the IP address. Either IPv4 or
IPv6 addresses may be supplied; integers less than 2**32 will
be considered to be IPv4 by default.
Returns:
An IPv4Address or IPv6Address object.
Raises:
ValueError: if the *address* passed isn't either a v4 or a v6
address | [
"Take",
"an",
"IP",
"string",
"/",
"int",
"and",
"return",
"an",
"object",
"of",
"the",
"correct",
"type",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L93-L120 | train |
saltstack/salt | salt/ext/ipaddress.py | ip_network | def ip_network(address, strict=True):
"""Take an IP string/int and return an object of the correct type.
Args:
address: A string or integer, the IP network. Either IPv4 or
IPv6 networks may be supplied; integers less than 2**32 will
be considered to be IPv4 by default.
Returns:
An IPv4Network or IPv6Network object.
Raises:
ValueError: if the string passed isn't either a v4 or a v6
address. Or if the network has host bits set.
"""
try:
return IPv4Network(address, strict)
except (AddressValueError, NetmaskValueError):
pass
try:
return IPv6Network(address, strict)
except (AddressValueError, NetmaskValueError):
pass
raise ValueError('%r does not appear to be an IPv4 or IPv6 network' %
address) | python | def ip_network(address, strict=True):
"""Take an IP string/int and return an object of the correct type.
Args:
address: A string or integer, the IP network. Either IPv4 or
IPv6 networks may be supplied; integers less than 2**32 will
be considered to be IPv4 by default.
Returns:
An IPv4Network or IPv6Network object.
Raises:
ValueError: if the string passed isn't either a v4 or a v6
address. Or if the network has host bits set.
"""
try:
return IPv4Network(address, strict)
except (AddressValueError, NetmaskValueError):
pass
try:
return IPv6Network(address, strict)
except (AddressValueError, NetmaskValueError):
pass
raise ValueError('%r does not appear to be an IPv4 or IPv6 network' %
address) | [
"def",
"ip_network",
"(",
"address",
",",
"strict",
"=",
"True",
")",
":",
"try",
":",
"return",
"IPv4Network",
"(",
"address",
",",
"strict",
")",
"except",
"(",
"AddressValueError",
",",
"NetmaskValueError",
")",
":",
"pass",
"try",
":",
"return",
"IPv6N... | Take an IP string/int and return an object of the correct type.
Args:
address: A string or integer, the IP network. Either IPv4 or
IPv6 networks may be supplied; integers less than 2**32 will
be considered to be IPv4 by default.
Returns:
An IPv4Network or IPv6Network object.
Raises:
ValueError: if the string passed isn't either a v4 or a v6
address. Or if the network has host bits set. | [
"Take",
"an",
"IP",
"string",
"/",
"int",
"and",
"return",
"an",
"object",
"of",
"the",
"correct",
"type",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L123-L150 | train |
saltstack/salt | salt/ext/ipaddress.py | _split_optional_netmask | def _split_optional_netmask(address):
"""Helper to split the netmask and raise AddressValueError if needed"""
addr = str(address).split('/')
if len(addr) > 2:
raise AddressValueError("Only one '/' permitted in %r" % address)
return addr | python | def _split_optional_netmask(address):
"""Helper to split the netmask and raise AddressValueError if needed"""
addr = str(address).split('/')
if len(addr) > 2:
raise AddressValueError("Only one '/' permitted in %r" % address)
return addr | [
"def",
"_split_optional_netmask",
"(",
"address",
")",
":",
"addr",
"=",
"str",
"(",
"address",
")",
".",
"split",
"(",
"'/'",
")",
"if",
"len",
"(",
"addr",
")",
">",
"2",
":",
"raise",
"AddressValueError",
"(",
"\"Only one '/' permitted in %r\"",
"%",
"a... | Helper to split the netmask and raise AddressValueError if needed | [
"Helper",
"to",
"split",
"the",
"netmask",
"and",
"raise",
"AddressValueError",
"if",
"needed"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L224-L229 | train |
saltstack/salt | salt/ext/ipaddress.py | _count_righthand_zero_bits | def _count_righthand_zero_bits(number, bits):
"""Count the number of zero bits on the right hand side.
Args:
number: an integer.
bits: maximum number of bits to count.
Returns:
The number of zero bits on the right hand side of the number.
"""
if number == 0:
return bits
for i in range(bits):
if (number >> i) & 1:
return i
# All bits of interest were zero, even if there are more in the number
return bits | python | def _count_righthand_zero_bits(number, bits):
"""Count the number of zero bits on the right hand side.
Args:
number: an integer.
bits: maximum number of bits to count.
Returns:
The number of zero bits on the right hand side of the number.
"""
if number == 0:
return bits
for i in range(bits):
if (number >> i) & 1:
return i
# All bits of interest were zero, even if there are more in the number
return bits | [
"def",
"_count_righthand_zero_bits",
"(",
"number",
",",
"bits",
")",
":",
"if",
"number",
"==",
"0",
":",
"return",
"bits",
"for",
"i",
"in",
"range",
"(",
"bits",
")",
":",
"if",
"(",
"number",
">>",
"i",
")",
"&",
"1",
":",
"return",
"i",
"# All... | Count the number of zero bits on the right hand side.
Args:
number: an integer.
bits: maximum number of bits to count.
Returns:
The number of zero bits on the right hand side of the number. | [
"Count",
"the",
"number",
"of",
"zero",
"bits",
"on",
"the",
"right",
"hand",
"side",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L251-L268 | train |
saltstack/salt | salt/ext/ipaddress.py | _collapse_addresses_recursive | def _collapse_addresses_recursive(addresses):
"""Loops through the addresses, collapsing concurrent netblocks.
Example:
ip1 = IPv4Network('192.0.2.0/26')
ip2 = IPv4Network('192.0.2.64/26')
ip3 = IPv4Network('192.0.2.128/26')
ip4 = IPv4Network('192.0.2.192/26')
_collapse_addresses_recursive([ip1, ip2, ip3, ip4]) ->
[IPv4Network('192.0.2.0/24')]
This shouldn't be called directly; it is called via
collapse_addresses([]).
Args:
addresses: A list of IPv4Network's or IPv6Network's
Returns:
A list of IPv4Network's or IPv6Network's depending on what we were
passed.
"""
while True:
last_addr = None
ret_array = []
optimized = False
for cur_addr in addresses:
if not ret_array:
last_addr = cur_addr
ret_array.append(cur_addr)
elif (cur_addr.network_address >= last_addr.network_address and
cur_addr.broadcast_address <= last_addr.broadcast_address):
optimized = True
elif cur_addr == list(last_addr.supernet().subnets())[1]:
ret_array[-1] = last_addr = last_addr.supernet()
optimized = True
else:
last_addr = cur_addr
ret_array.append(cur_addr)
addresses = ret_array
if not optimized:
return addresses | python | def _collapse_addresses_recursive(addresses):
"""Loops through the addresses, collapsing concurrent netblocks.
Example:
ip1 = IPv4Network('192.0.2.0/26')
ip2 = IPv4Network('192.0.2.64/26')
ip3 = IPv4Network('192.0.2.128/26')
ip4 = IPv4Network('192.0.2.192/26')
_collapse_addresses_recursive([ip1, ip2, ip3, ip4]) ->
[IPv4Network('192.0.2.0/24')]
This shouldn't be called directly; it is called via
collapse_addresses([]).
Args:
addresses: A list of IPv4Network's or IPv6Network's
Returns:
A list of IPv4Network's or IPv6Network's depending on what we were
passed.
"""
while True:
last_addr = None
ret_array = []
optimized = False
for cur_addr in addresses:
if not ret_array:
last_addr = cur_addr
ret_array.append(cur_addr)
elif (cur_addr.network_address >= last_addr.network_address and
cur_addr.broadcast_address <= last_addr.broadcast_address):
optimized = True
elif cur_addr == list(last_addr.supernet().subnets())[1]:
ret_array[-1] = last_addr = last_addr.supernet()
optimized = True
else:
last_addr = cur_addr
ret_array.append(cur_addr)
addresses = ret_array
if not optimized:
return addresses | [
"def",
"_collapse_addresses_recursive",
"(",
"addresses",
")",
":",
"while",
"True",
":",
"last_addr",
"=",
"None",
"ret_array",
"=",
"[",
"]",
"optimized",
"=",
"False",
"for",
"cur_addr",
"in",
"addresses",
":",
"if",
"not",
"ret_array",
":",
"last_addr",
... | Loops through the addresses, collapsing concurrent netblocks.
Example:
ip1 = IPv4Network('192.0.2.0/26')
ip2 = IPv4Network('192.0.2.64/26')
ip3 = IPv4Network('192.0.2.128/26')
ip4 = IPv4Network('192.0.2.192/26')
_collapse_addresses_recursive([ip1, ip2, ip3, ip4]) ->
[IPv4Network('192.0.2.0/24')]
This shouldn't be called directly; it is called via
collapse_addresses([]).
Args:
addresses: A list of IPv4Network's or IPv6Network's
Returns:
A list of IPv4Network's or IPv6Network's depending on what we were
passed. | [
"Loops",
"through",
"the",
"addresses",
"collapsing",
"concurrent",
"netblocks",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L327-L372 | train |
saltstack/salt | salt/ext/ipaddress.py | collapse_addresses | def collapse_addresses(addresses):
"""Collapse a list of IP objects.
Example:
collapse_addresses([IPv4Network('192.0.2.0/25'),
IPv4Network('192.0.2.128/25')]) ->
[IPv4Network('192.0.2.0/24')]
Args:
addresses: An iterator of IPv4Network or IPv6Network objects.
Returns:
An iterator of the collapsed IPv(4|6)Network objects.
Raises:
TypeError: If passed a list of mixed version objects.
"""
i = 0
addrs = []
ips = []
nets = []
# split IP addresses and networks
for ip in addresses:
if isinstance(ip, _BaseAddress):
if ips and ips[-1]._version != ip._version:
raise TypeError("%s and %s are not of the same version" % (
ip, ips[-1]))
ips.append(ip)
elif ip._prefixlen == ip._max_prefixlen:
if ips and ips[-1]._version != ip._version:
raise TypeError("%s and %s are not of the same version" % (
ip, ips[-1]))
try:
ips.append(ip.ip)
except AttributeError:
ips.append(ip.network_address)
else:
if nets and nets[-1]._version != ip._version:
raise TypeError("%s and %s are not of the same version" % (
ip, nets[-1]))
nets.append(ip)
# sort and dedup
ips = sorted(set(ips))
nets = sorted(set(nets))
while i < len(ips):
(first, last) = _find_address_range(ips[i:])
i = ips.index(last) + 1
addrs.extend(summarize_address_range(first, last))
return iter(_collapse_addresses_recursive(sorted(
addrs + nets, key=_BaseNetwork._get_networks_key))) | python | def collapse_addresses(addresses):
"""Collapse a list of IP objects.
Example:
collapse_addresses([IPv4Network('192.0.2.0/25'),
IPv4Network('192.0.2.128/25')]) ->
[IPv4Network('192.0.2.0/24')]
Args:
addresses: An iterator of IPv4Network or IPv6Network objects.
Returns:
An iterator of the collapsed IPv(4|6)Network objects.
Raises:
TypeError: If passed a list of mixed version objects.
"""
i = 0
addrs = []
ips = []
nets = []
# split IP addresses and networks
for ip in addresses:
if isinstance(ip, _BaseAddress):
if ips and ips[-1]._version != ip._version:
raise TypeError("%s and %s are not of the same version" % (
ip, ips[-1]))
ips.append(ip)
elif ip._prefixlen == ip._max_prefixlen:
if ips and ips[-1]._version != ip._version:
raise TypeError("%s and %s are not of the same version" % (
ip, ips[-1]))
try:
ips.append(ip.ip)
except AttributeError:
ips.append(ip.network_address)
else:
if nets and nets[-1]._version != ip._version:
raise TypeError("%s and %s are not of the same version" % (
ip, nets[-1]))
nets.append(ip)
# sort and dedup
ips = sorted(set(ips))
nets = sorted(set(nets))
while i < len(ips):
(first, last) = _find_address_range(ips[i:])
i = ips.index(last) + 1
addrs.extend(summarize_address_range(first, last))
return iter(_collapse_addresses_recursive(sorted(
addrs + nets, key=_BaseNetwork._get_networks_key))) | [
"def",
"collapse_addresses",
"(",
"addresses",
")",
":",
"i",
"=",
"0",
"addrs",
"=",
"[",
"]",
"ips",
"=",
"[",
"]",
"nets",
"=",
"[",
"]",
"# split IP addresses and networks",
"for",
"ip",
"in",
"addresses",
":",
"if",
"isinstance",
"(",
"ip",
",",
"... | Collapse a list of IP objects.
Example:
collapse_addresses([IPv4Network('192.0.2.0/25'),
IPv4Network('192.0.2.128/25')]) ->
[IPv4Network('192.0.2.0/24')]
Args:
addresses: An iterator of IPv4Network or IPv6Network objects.
Returns:
An iterator of the collapsed IPv(4|6)Network objects.
Raises:
TypeError: If passed a list of mixed version objects. | [
"Collapse",
"a",
"list",
"of",
"IP",
"objects",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L375-L429 | train |
saltstack/salt | salt/ext/ipaddress.py | _IPAddressBase._prefix_from_ip_int | def _prefix_from_ip_int(self, ip_int):
"""Return prefix length from the bitwise netmask.
Args:
ip_int: An integer, the netmask in expanded bitwise format
Returns:
An integer, the prefix length.
Raises:
ValueError: If the input intermingles zeroes & ones
"""
trailing_zeroes = _count_righthand_zero_bits(ip_int,
self._max_prefixlen)
prefixlen = self._max_prefixlen - trailing_zeroes
leading_ones = ip_int >> trailing_zeroes
all_ones = (1 << prefixlen) - 1
if leading_ones != all_ones:
byteslen = self._max_prefixlen // 8
details = _int_to_bytes(ip_int, byteslen, 'big')
msg = 'Netmask pattern %r mixes zeroes & ones'
raise ValueError(msg % details)
return prefixlen | python | def _prefix_from_ip_int(self, ip_int):
"""Return prefix length from the bitwise netmask.
Args:
ip_int: An integer, the netmask in expanded bitwise format
Returns:
An integer, the prefix length.
Raises:
ValueError: If the input intermingles zeroes & ones
"""
trailing_zeroes = _count_righthand_zero_bits(ip_int,
self._max_prefixlen)
prefixlen = self._max_prefixlen - trailing_zeroes
leading_ones = ip_int >> trailing_zeroes
all_ones = (1 << prefixlen) - 1
if leading_ones != all_ones:
byteslen = self._max_prefixlen // 8
details = _int_to_bytes(ip_int, byteslen, 'big')
msg = 'Netmask pattern %r mixes zeroes & ones'
raise ValueError(msg % details)
return prefixlen | [
"def",
"_prefix_from_ip_int",
"(",
"self",
",",
"ip_int",
")",
":",
"trailing_zeroes",
"=",
"_count_righthand_zero_bits",
"(",
"ip_int",
",",
"self",
".",
"_max_prefixlen",
")",
"prefixlen",
"=",
"self",
".",
"_max_prefixlen",
"-",
"trailing_zeroes",
"leading_ones",... | Return prefix length from the bitwise netmask.
Args:
ip_int: An integer, the netmask in expanded bitwise format
Returns:
An integer, the prefix length.
Raises:
ValueError: If the input intermingles zeroes & ones | [
"Return",
"prefix",
"length",
"from",
"the",
"bitwise",
"netmask",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L548-L570 | train |
saltstack/salt | salt/ext/ipaddress.py | _IPAddressBase._prefix_from_prefix_string | def _prefix_from_prefix_string(self, prefixlen_str):
"""Return prefix length from a numeric string
Args:
prefixlen_str: The string to be converted
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask
"""
# int allows a leading +/- as well as surrounding whitespace,
# so we ensure that isn't the case
if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str):
self._report_invalid_netmask(prefixlen_str)
try:
prefixlen = int(prefixlen_str)
except ValueError:
self._report_invalid_netmask(prefixlen_str)
if not (0 <= prefixlen <= self._max_prefixlen):
self._report_invalid_netmask(prefixlen_str)
return prefixlen | python | def _prefix_from_prefix_string(self, prefixlen_str):
"""Return prefix length from a numeric string
Args:
prefixlen_str: The string to be converted
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask
"""
# int allows a leading +/- as well as surrounding whitespace,
# so we ensure that isn't the case
if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str):
self._report_invalid_netmask(prefixlen_str)
try:
prefixlen = int(prefixlen_str)
except ValueError:
self._report_invalid_netmask(prefixlen_str)
if not (0 <= prefixlen <= self._max_prefixlen):
self._report_invalid_netmask(prefixlen_str)
return prefixlen | [
"def",
"_prefix_from_prefix_string",
"(",
"self",
",",
"prefixlen_str",
")",
":",
"# int allows a leading +/- as well as surrounding whitespace,",
"# so we ensure that isn't the case",
"if",
"not",
"_BaseV4",
".",
"_DECIMAL_DIGITS",
".",
"issuperset",
"(",
"prefixlen_str",
")",... | Return prefix length from a numeric string
Args:
prefixlen_str: The string to be converted
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask | [
"Return",
"prefix",
"length",
"from",
"a",
"numeric",
"string"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L576-L598 | train |
saltstack/salt | salt/ext/ipaddress.py | _IPAddressBase._prefix_from_ip_string | def _prefix_from_ip_string(self, ip_str):
"""Turn a netmask/hostmask string into a prefix length
Args:
ip_str: The netmask/hostmask to be converted
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask/hostmask
"""
# Parse the netmask/hostmask like an IP address.
try:
ip_int = self._ip_int_from_string(ip_str)
except AddressValueError:
self._report_invalid_netmask(ip_str)
# Try matching a netmask (this would be /1*0*/ as a bitwise regexp).
# Note that the two ambiguous cases (all-ones and all-zeroes) are
# treated as netmasks.
try:
return self._prefix_from_ip_int(ip_int)
except ValueError:
pass
# Invert the bits, and try matching a /0+1+/ hostmask instead.
ip_int ^= self._ALL_ONES
try:
return self._prefix_from_ip_int(ip_int)
except ValueError:
self._report_invalid_netmask(ip_str) | python | def _prefix_from_ip_string(self, ip_str):
"""Turn a netmask/hostmask string into a prefix length
Args:
ip_str: The netmask/hostmask to be converted
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask/hostmask
"""
# Parse the netmask/hostmask like an IP address.
try:
ip_int = self._ip_int_from_string(ip_str)
except AddressValueError:
self._report_invalid_netmask(ip_str)
# Try matching a netmask (this would be /1*0*/ as a bitwise regexp).
# Note that the two ambiguous cases (all-ones and all-zeroes) are
# treated as netmasks.
try:
return self._prefix_from_ip_int(ip_int)
except ValueError:
pass
# Invert the bits, and try matching a /0+1+/ hostmask instead.
ip_int ^= self._ALL_ONES
try:
return self._prefix_from_ip_int(ip_int)
except ValueError:
self._report_invalid_netmask(ip_str) | [
"def",
"_prefix_from_ip_string",
"(",
"self",
",",
"ip_str",
")",
":",
"# Parse the netmask/hostmask like an IP address.",
"try",
":",
"ip_int",
"=",
"self",
".",
"_ip_int_from_string",
"(",
"ip_str",
")",
"except",
"AddressValueError",
":",
"self",
".",
"_report_inva... | Turn a netmask/hostmask string into a prefix length
Args:
ip_str: The netmask/hostmask to be converted
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask/hostmask | [
"Turn",
"a",
"netmask",
"/",
"hostmask",
"string",
"into",
"a",
"prefix",
"length"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L600-L631 | train |
saltstack/salt | salt/ext/ipaddress.py | _BaseNetwork.subnets | def subnets(self, prefixlen_diff=1, new_prefix=None):
"""The subnets which join to make the current subnet.
In the case that self contains only one IP
(self._prefixlen == 32 for IPv4 or self._prefixlen == 128
for IPv6), yield an iterator with just ourself.
Args:
prefixlen_diff: An integer, the amount the prefix length
should be increased by. This should not be set if
new_prefix is also set.
new_prefix: The desired new prefix length. This must be a
larger number (smaller prefix) than the existing prefix.
This should not be set if prefixlen_diff is also set.
Returns:
An iterator of IPv(4|6) objects.
Raises:
ValueError: The prefixlen_diff is too small or too large.
OR
prefixlen_diff and new_prefix are both set or new_prefix
is a smaller number than the current prefix (smaller
number means a larger network)
"""
if self._prefixlen == self._max_prefixlen:
yield self
return
if new_prefix is not None:
if new_prefix < self._prefixlen:
raise ValueError('new prefix must be longer')
if prefixlen_diff != 1:
raise ValueError('cannot set prefixlen_diff and new_prefix')
prefixlen_diff = new_prefix - self._prefixlen
if prefixlen_diff < 0:
raise ValueError('prefix length diff must be > 0')
new_prefixlen = self._prefixlen + prefixlen_diff
if new_prefixlen > self._max_prefixlen:
raise ValueError(
'prefix length diff %d is invalid for netblock %s' % (
new_prefixlen, self))
first = self.__class__('%s/%s' %
(self.network_address,
self._prefixlen + prefixlen_diff))
yield first
current = first
while True:
broadcast = current.broadcast_address
if broadcast == self.broadcast_address:
return
new_addr = self._address_class(int(broadcast) + 1)
current = self.__class__('%s/%s' % (new_addr,
new_prefixlen))
yield current | python | def subnets(self, prefixlen_diff=1, new_prefix=None):
"""The subnets which join to make the current subnet.
In the case that self contains only one IP
(self._prefixlen == 32 for IPv4 or self._prefixlen == 128
for IPv6), yield an iterator with just ourself.
Args:
prefixlen_diff: An integer, the amount the prefix length
should be increased by. This should not be set if
new_prefix is also set.
new_prefix: The desired new prefix length. This must be a
larger number (smaller prefix) than the existing prefix.
This should not be set if prefixlen_diff is also set.
Returns:
An iterator of IPv(4|6) objects.
Raises:
ValueError: The prefixlen_diff is too small or too large.
OR
prefixlen_diff and new_prefix are both set or new_prefix
is a smaller number than the current prefix (smaller
number means a larger network)
"""
if self._prefixlen == self._max_prefixlen:
yield self
return
if new_prefix is not None:
if new_prefix < self._prefixlen:
raise ValueError('new prefix must be longer')
if prefixlen_diff != 1:
raise ValueError('cannot set prefixlen_diff and new_prefix')
prefixlen_diff = new_prefix - self._prefixlen
if prefixlen_diff < 0:
raise ValueError('prefix length diff must be > 0')
new_prefixlen = self._prefixlen + prefixlen_diff
if new_prefixlen > self._max_prefixlen:
raise ValueError(
'prefix length diff %d is invalid for netblock %s' % (
new_prefixlen, self))
first = self.__class__('%s/%s' %
(self.network_address,
self._prefixlen + prefixlen_diff))
yield first
current = first
while True:
broadcast = current.broadcast_address
if broadcast == self.broadcast_address:
return
new_addr = self._address_class(int(broadcast) + 1)
current = self.__class__('%s/%s' % (new_addr,
new_prefixlen))
yield current | [
"def",
"subnets",
"(",
"self",
",",
"prefixlen_diff",
"=",
"1",
",",
"new_prefix",
"=",
"None",
")",
":",
"if",
"self",
".",
"_prefixlen",
"==",
"self",
".",
"_max_prefixlen",
":",
"yield",
"self",
"return",
"if",
"new_prefix",
"is",
"not",
"None",
":",
... | The subnets which join to make the current subnet.
In the case that self contains only one IP
(self._prefixlen == 32 for IPv4 or self._prefixlen == 128
for IPv6), yield an iterator with just ourself.
Args:
prefixlen_diff: An integer, the amount the prefix length
should be increased by. This should not be set if
new_prefix is also set.
new_prefix: The desired new prefix length. This must be a
larger number (smaller prefix) than the existing prefix.
This should not be set if prefixlen_diff is also set.
Returns:
An iterator of IPv(4|6) objects.
Raises:
ValueError: The prefixlen_diff is too small or too large.
OR
prefixlen_diff and new_prefix are both set or new_prefix
is a smaller number than the current prefix (smaller
number means a larger network) | [
"The",
"subnets",
"which",
"join",
"to",
"make",
"the",
"current",
"subnet",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L967-L1027 | train |
saltstack/salt | salt/ext/ipaddress.py | _BaseNetwork.supernet | def supernet(self, prefixlen_diff=1, new_prefix=None):
"""The supernet containing the current network.
Args:
prefixlen_diff: An integer, the amount the prefix length of
the network should be decreased by. For example, given a
/24 network and a prefixlen_diff of 3, a supernet with a
/21 netmask is returned.
Returns:
An IPv4 network object.
Raises:
ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
a negative prefix length.
OR
If prefixlen_diff and new_prefix are both set or new_prefix is a
larger number than the current prefix (larger number means a
smaller network)
"""
if self._prefixlen == 0:
return self
if new_prefix is not None:
if new_prefix > self._prefixlen:
raise ValueError('new prefix must be shorter')
if prefixlen_diff != 1:
raise ValueError('cannot set prefixlen_diff and new_prefix')
prefixlen_diff = self._prefixlen - new_prefix
if self.prefixlen - prefixlen_diff < 0:
raise ValueError(
'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
(self.prefixlen, prefixlen_diff))
# TODO (pmoody): optimize this.
t = self.__class__('%s/%d' % (self.network_address,
self.prefixlen - prefixlen_diff),
strict=False)
return t.__class__('%s/%d' % (t.network_address, t.prefixlen)) | python | def supernet(self, prefixlen_diff=1, new_prefix=None):
"""The supernet containing the current network.
Args:
prefixlen_diff: An integer, the amount the prefix length of
the network should be decreased by. For example, given a
/24 network and a prefixlen_diff of 3, a supernet with a
/21 netmask is returned.
Returns:
An IPv4 network object.
Raises:
ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
a negative prefix length.
OR
If prefixlen_diff and new_prefix are both set or new_prefix is a
larger number than the current prefix (larger number means a
smaller network)
"""
if self._prefixlen == 0:
return self
if new_prefix is not None:
if new_prefix > self._prefixlen:
raise ValueError('new prefix must be shorter')
if prefixlen_diff != 1:
raise ValueError('cannot set prefixlen_diff and new_prefix')
prefixlen_diff = self._prefixlen - new_prefix
if self.prefixlen - prefixlen_diff < 0:
raise ValueError(
'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
(self.prefixlen, prefixlen_diff))
# TODO (pmoody): optimize this.
t = self.__class__('%s/%d' % (self.network_address,
self.prefixlen - prefixlen_diff),
strict=False)
return t.__class__('%s/%d' % (t.network_address, t.prefixlen)) | [
"def",
"supernet",
"(",
"self",
",",
"prefixlen_diff",
"=",
"1",
",",
"new_prefix",
"=",
"None",
")",
":",
"if",
"self",
".",
"_prefixlen",
"==",
"0",
":",
"return",
"self",
"if",
"new_prefix",
"is",
"not",
"None",
":",
"if",
"new_prefix",
">",
"self",... | The supernet containing the current network.
Args:
prefixlen_diff: An integer, the amount the prefix length of
the network should be decreased by. For example, given a
/24 network and a prefixlen_diff of 3, a supernet with a
/21 netmask is returned.
Returns:
An IPv4 network object.
Raises:
ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
a negative prefix length.
OR
If prefixlen_diff and new_prefix are both set or new_prefix is a
larger number than the current prefix (larger number means a
smaller network) | [
"The",
"supernet",
"containing",
"the",
"current",
"network",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L1029-L1068 | train |
saltstack/salt | salt/ext/ipaddress.py | _BaseV4._ip_int_from_string | def _ip_int_from_string(self, ip_str):
"""Turn the given IP string into an integer for comparison.
Args:
ip_str: A string, the IP ip_str.
Returns:
The IP ip_str as an integer.
Raises:
AddressValueError: if ip_str isn't a valid IPv4 Address.
"""
if not ip_str:
raise AddressValueError('Address cannot be empty')
octets = ip_str.split('.')
if len(octets) != 4:
raise AddressValueError("Expected 4 octets in %r" % ip_str)
try:
return _int_from_bytes(map(self._parse_octet, octets), 'big')
except ValueError as exc:
raise AddressValueError("%s in %r" % (exc, ip_str)) | python | def _ip_int_from_string(self, ip_str):
"""Turn the given IP string into an integer for comparison.
Args:
ip_str: A string, the IP ip_str.
Returns:
The IP ip_str as an integer.
Raises:
AddressValueError: if ip_str isn't a valid IPv4 Address.
"""
if not ip_str:
raise AddressValueError('Address cannot be empty')
octets = ip_str.split('.')
if len(octets) != 4:
raise AddressValueError("Expected 4 octets in %r" % ip_str)
try:
return _int_from_bytes(map(self._parse_octet, octets), 'big')
except ValueError as exc:
raise AddressValueError("%s in %r" % (exc, ip_str)) | [
"def",
"_ip_int_from_string",
"(",
"self",
",",
"ip_str",
")",
":",
"if",
"not",
"ip_str",
":",
"raise",
"AddressValueError",
"(",
"'Address cannot be empty'",
")",
"octets",
"=",
"ip_str",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"octets",
")",
"!... | Turn the given IP string into an integer for comparison.
Args:
ip_str: A string, the IP ip_str.
Returns:
The IP ip_str as an integer.
Raises:
AddressValueError: if ip_str isn't a valid IPv4 Address. | [
"Turn",
"the",
"given",
"IP",
"string",
"into",
"an",
"integer",
"for",
"comparison",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L1176-L1199 | train |
saltstack/salt | salt/ext/ipaddress.py | _BaseV4._parse_octet | def _parse_octet(self, octet_str):
"""Convert a decimal octet into an integer.
Args:
octet_str: A string, the number to parse.
Returns:
The octet as an integer.
Raises:
ValueError: if the octet isn't strictly a decimal from [0..255].
"""
if not octet_str:
raise ValueError("Empty octet not permitted")
# Whitelist the characters, since int() allows a lot of bizarre stuff.
if not self._DECIMAL_DIGITS.issuperset(octet_str):
msg = "Only decimal digits permitted in %r"
raise ValueError(msg % octet_str)
# We do the length check second, since the invalid character error
# is likely to be more informative for the user
if len(octet_str) > 3:
msg = "At most 3 characters permitted in %r"
raise ValueError(msg % octet_str)
# Convert to integer (we know digits are legal)
octet_int = int(octet_str, 10)
# Any octets that look like they *might* be written in octal,
# and which don't look exactly the same in both octal and
# decimal are rejected as ambiguous
if octet_int > 7 and octet_str[0] == '0':
msg = "Ambiguous (octal/decimal) value in %r not permitted"
raise ValueError(msg % octet_str)
if octet_int > 255:
raise ValueError("Octet %d (> 255) not permitted" % octet_int)
return octet_int | python | def _parse_octet(self, octet_str):
"""Convert a decimal octet into an integer.
Args:
octet_str: A string, the number to parse.
Returns:
The octet as an integer.
Raises:
ValueError: if the octet isn't strictly a decimal from [0..255].
"""
if not octet_str:
raise ValueError("Empty octet not permitted")
# Whitelist the characters, since int() allows a lot of bizarre stuff.
if not self._DECIMAL_DIGITS.issuperset(octet_str):
msg = "Only decimal digits permitted in %r"
raise ValueError(msg % octet_str)
# We do the length check second, since the invalid character error
# is likely to be more informative for the user
if len(octet_str) > 3:
msg = "At most 3 characters permitted in %r"
raise ValueError(msg % octet_str)
# Convert to integer (we know digits are legal)
octet_int = int(octet_str, 10)
# Any octets that look like they *might* be written in octal,
# and which don't look exactly the same in both octal and
# decimal are rejected as ambiguous
if octet_int > 7 and octet_str[0] == '0':
msg = "Ambiguous (octal/decimal) value in %r not permitted"
raise ValueError(msg % octet_str)
if octet_int > 255:
raise ValueError("Octet %d (> 255) not permitted" % octet_int)
return octet_int | [
"def",
"_parse_octet",
"(",
"self",
",",
"octet_str",
")",
":",
"if",
"not",
"octet_str",
":",
"raise",
"ValueError",
"(",
"\"Empty octet not permitted\"",
")",
"# Whitelist the characters, since int() allows a lot of bizarre stuff.",
"if",
"not",
"self",
".",
"_DECIMAL_D... | Convert a decimal octet into an integer.
Args:
octet_str: A string, the number to parse.
Returns:
The octet as an integer.
Raises:
ValueError: if the octet isn't strictly a decimal from [0..255]. | [
"Convert",
"a",
"decimal",
"octet",
"into",
"an",
"integer",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L1201-L1235 | train |
saltstack/salt | salt/ext/ipaddress.py | _BaseV4._is_valid_netmask | def _is_valid_netmask(self, netmask):
"""Verify that the netmask is valid.
Args:
netmask: A string, either a prefix or dotted decimal
netmask.
Returns:
A boolean, True if the prefix represents a valid IPv4
netmask.
"""
mask = netmask.split('.')
if len(mask) == 4:
try:
for x in mask:
if int(x) not in self._valid_mask_octets:
return False
except ValueError:
# Found something that isn't an integer or isn't valid
return False
for idx, y in enumerate(mask):
if idx > 0 and y > mask[idx - 1]:
return False
return True
try:
netmask = int(netmask)
except ValueError:
return False
return 0 <= netmask <= self._max_prefixlen | python | def _is_valid_netmask(self, netmask):
"""Verify that the netmask is valid.
Args:
netmask: A string, either a prefix or dotted decimal
netmask.
Returns:
A boolean, True if the prefix represents a valid IPv4
netmask.
"""
mask = netmask.split('.')
if len(mask) == 4:
try:
for x in mask:
if int(x) not in self._valid_mask_octets:
return False
except ValueError:
# Found something that isn't an integer or isn't valid
return False
for idx, y in enumerate(mask):
if idx > 0 and y > mask[idx - 1]:
return False
return True
try:
netmask = int(netmask)
except ValueError:
return False
return 0 <= netmask <= self._max_prefixlen | [
"def",
"_is_valid_netmask",
"(",
"self",
",",
"netmask",
")",
":",
"mask",
"=",
"netmask",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"mask",
")",
"==",
"4",
":",
"try",
":",
"for",
"x",
"in",
"mask",
":",
"if",
"int",
"(",
"x",
")",
"not... | Verify that the netmask is valid.
Args:
netmask: A string, either a prefix or dotted decimal
netmask.
Returns:
A boolean, True if the prefix represents a valid IPv4
netmask. | [
"Verify",
"that",
"the",
"netmask",
"is",
"valid",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L1249-L1278 | train |
saltstack/salt | salt/ext/ipaddress.py | IPv4Address.is_private | def is_private(self):
"""Test if this address is allocated for private networks.
Returns:
A boolean, True if the address is reserved per
iana-ipv4-special-registry.
"""
return (self in IPv4Network('0.0.0.0/8') or
self in IPv4Network('10.0.0.0/8') or
self in IPv4Network('127.0.0.0/8') or
self in IPv4Network('169.254.0.0/16') or
self in IPv4Network('172.16.0.0/12') or
self in IPv4Network('192.0.0.0/29') or
self in IPv4Network('192.0.0.170/31') or
self in IPv4Network('192.0.2.0/24') or
self in IPv4Network('192.168.0.0/16') or
self in IPv4Network('198.18.0.0/15') or
self in IPv4Network('198.51.100.0/24') or
self in IPv4Network('203.0.113.0/24') or
self in IPv4Network('240.0.0.0/4') or
self in IPv4Network('255.255.255.255/32')) | python | def is_private(self):
"""Test if this address is allocated for private networks.
Returns:
A boolean, True if the address is reserved per
iana-ipv4-special-registry.
"""
return (self in IPv4Network('0.0.0.0/8') or
self in IPv4Network('10.0.0.0/8') or
self in IPv4Network('127.0.0.0/8') or
self in IPv4Network('169.254.0.0/16') or
self in IPv4Network('172.16.0.0/12') or
self in IPv4Network('192.0.0.0/29') or
self in IPv4Network('192.0.0.170/31') or
self in IPv4Network('192.0.2.0/24') or
self in IPv4Network('192.168.0.0/16') or
self in IPv4Network('198.18.0.0/15') or
self in IPv4Network('198.51.100.0/24') or
self in IPv4Network('203.0.113.0/24') or
self in IPv4Network('240.0.0.0/4') or
self in IPv4Network('255.255.255.255/32')) | [
"def",
"is_private",
"(",
"self",
")",
":",
"return",
"(",
"self",
"in",
"IPv4Network",
"(",
"'0.0.0.0/8'",
")",
"or",
"self",
"in",
"IPv4Network",
"(",
"'10.0.0.0/8'",
")",
"or",
"self",
"in",
"IPv4Network",
"(",
"'127.0.0.0/8'",
")",
"or",
"self",
"in",
... | Test if this address is allocated for private networks.
Returns:
A boolean, True if the address is reserved per
iana-ipv4-special-registry. | [
"Test",
"if",
"this",
"address",
"is",
"allocated",
"for",
"private",
"networks",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L1377-L1398 | train |
saltstack/salt | salt/ext/ipaddress.py | _BaseV6._explode_shorthand_ip_string | def _explode_shorthand_ip_string(self):
"""Expand a shortened IPv6 address.
Args:
ip_str: A string, the IPv6 address.
Returns:
A string, the expanded IPv6 address.
"""
if isinstance(self, IPv6Network):
ip_str = str(self.network_address)
elif isinstance(self, IPv6Interface):
ip_str = str(self.ip)
else:
ip_str = str(self)
ip_int = self._ip_int_from_string(ip_str)
hex_str = '%032x' % ip_int
parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
if isinstance(self, (_BaseNetwork, IPv6Interface)):
return '%s/%d' % (':'.join(parts), self._prefixlen)
return ':'.join(parts) | python | def _explode_shorthand_ip_string(self):
"""Expand a shortened IPv6 address.
Args:
ip_str: A string, the IPv6 address.
Returns:
A string, the expanded IPv6 address.
"""
if isinstance(self, IPv6Network):
ip_str = str(self.network_address)
elif isinstance(self, IPv6Interface):
ip_str = str(self.ip)
else:
ip_str = str(self)
ip_int = self._ip_int_from_string(ip_str)
hex_str = '%032x' % ip_int
parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
if isinstance(self, (_BaseNetwork, IPv6Interface)):
return '%s/%d' % (':'.join(parts), self._prefixlen)
return ':'.join(parts) | [
"def",
"_explode_shorthand_ip_string",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
",",
"IPv6Network",
")",
":",
"ip_str",
"=",
"str",
"(",
"self",
".",
"network_address",
")",
"elif",
"isinstance",
"(",
"self",
",",
"IPv6Interface",
")",
":",
... | Expand a shortened IPv6 address.
Args:
ip_str: A string, the IPv6 address.
Returns:
A string, the expanded IPv6 address. | [
"Expand",
"a",
"shortened",
"IPv6",
"address",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L1847-L1869 | train |
saltstack/salt | salt/ext/ipaddress.py | IPv6Address.is_reserved | def is_reserved(self):
"""Test if the address is otherwise IETF reserved.
Returns:
A boolean, True if the address is within one of the
reserved IPv6 Network ranges.
"""
reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'),
IPv6Network('200::/7'), IPv6Network('400::/6'),
IPv6Network('800::/5'), IPv6Network('1000::/4'),
IPv6Network('4000::/3'), IPv6Network('6000::/3'),
IPv6Network('8000::/3'), IPv6Network('A000::/3'),
IPv6Network('C000::/3'), IPv6Network('E000::/4'),
IPv6Network('F000::/5'), IPv6Network('F800::/6'),
IPv6Network('FE00::/9')]
return any(self in x for x in reserved_networks) | python | def is_reserved(self):
"""Test if the address is otherwise IETF reserved.
Returns:
A boolean, True if the address is within one of the
reserved IPv6 Network ranges.
"""
reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'),
IPv6Network('200::/7'), IPv6Network('400::/6'),
IPv6Network('800::/5'), IPv6Network('1000::/4'),
IPv6Network('4000::/3'), IPv6Network('6000::/3'),
IPv6Network('8000::/3'), IPv6Network('A000::/3'),
IPv6Network('C000::/3'), IPv6Network('E000::/4'),
IPv6Network('F000::/5'), IPv6Network('F800::/6'),
IPv6Network('FE00::/9')]
return any(self in x for x in reserved_networks) | [
"def",
"is_reserved",
"(",
"self",
")",
":",
"reserved_networks",
"=",
"[",
"IPv6Network",
"(",
"'::/8'",
")",
",",
"IPv6Network",
"(",
"'100::/8'",
")",
",",
"IPv6Network",
"(",
"'200::/7'",
")",
",",
"IPv6Network",
"(",
"'400::/6'",
")",
",",
"IPv6Network"... | Test if the address is otherwise IETF reserved.
Returns:
A boolean, True if the address is within one of the
reserved IPv6 Network ranges. | [
"Test",
"if",
"the",
"address",
"is",
"otherwise",
"IETF",
"reserved",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L1948-L1965 | train |
saltstack/salt | salt/ext/ipaddress.py | IPv6Address.is_private | def is_private(self):
"""Test if this address is allocated for private networks.
Returns:
A boolean, True if the address is reserved per
iana-ipv6-special-registry.
"""
return (self in IPv6Network('::1/128') or
self in IPv6Network('::/128') or
self in IPv6Network('::ffff:0:0/96') or
self in IPv6Network('100::/64') or
self in IPv6Network('2001::/23') or
self in IPv6Network('2001:2::/48') or
self in IPv6Network('2001:db8::/32') or
self in IPv6Network('2001:10::/28') or
self in IPv6Network('fc00::/7') or
self in IPv6Network('fe80::/10')) | python | def is_private(self):
"""Test if this address is allocated for private networks.
Returns:
A boolean, True if the address is reserved per
iana-ipv6-special-registry.
"""
return (self in IPv6Network('::1/128') or
self in IPv6Network('::/128') or
self in IPv6Network('::ffff:0:0/96') or
self in IPv6Network('100::/64') or
self in IPv6Network('2001::/23') or
self in IPv6Network('2001:2::/48') or
self in IPv6Network('2001:db8::/32') or
self in IPv6Network('2001:10::/28') or
self in IPv6Network('fc00::/7') or
self in IPv6Network('fe80::/10')) | [
"def",
"is_private",
"(",
"self",
")",
":",
"return",
"(",
"self",
"in",
"IPv6Network",
"(",
"'::1/128'",
")",
"or",
"self",
"in",
"IPv6Network",
"(",
"'::/128'",
")",
"or",
"self",
"in",
"IPv6Network",
"(",
"'::ffff:0:0/96'",
")",
"or",
"self",
"in",
"I... | Test if this address is allocated for private networks.
Returns:
A boolean, True if the address is reserved per
iana-ipv6-special-registry. | [
"Test",
"if",
"this",
"address",
"is",
"allocated",
"for",
"private",
"networks",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L1994-L2011 | train |
saltstack/salt | salt/ext/ipaddress.py | IPv6Network.hosts | def hosts(self):
"""Generate Iterator over usable hosts in a network.
This is like __iter__ except it doesn't return the
Subnet-Router anycast address.
"""
network = int(self.network_address)
broadcast = int(self.broadcast_address)
for x in long_range(1, broadcast - network + 1):
yield self._address_class(network + x) | python | def hosts(self):
"""Generate Iterator over usable hosts in a network.
This is like __iter__ except it doesn't return the
Subnet-Router anycast address.
"""
network = int(self.network_address)
broadcast = int(self.broadcast_address)
for x in long_range(1, broadcast - network + 1):
yield self._address_class(network + x) | [
"def",
"hosts",
"(",
"self",
")",
":",
"network",
"=",
"int",
"(",
"self",
".",
"network_address",
")",
"broadcast",
"=",
"int",
"(",
"self",
".",
"broadcast_address",
")",
"for",
"x",
"in",
"long_range",
"(",
"1",
",",
"broadcast",
"-",
"network",
"+"... | Generate Iterator over usable hosts in a network.
This is like __iter__ except it doesn't return the
Subnet-Router anycast address. | [
"Generate",
"Iterator",
"over",
"usable",
"hosts",
"in",
"a",
"network",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L2250-L2260 | train |
saltstack/salt | salt/beacons/network_info.py | _to_list | def _to_list(obj):
'''
Convert snetinfo object to list
'''
ret = {}
for attr in __attrs:
if hasattr(obj, attr):
ret[attr] = getattr(obj, attr)
return ret | python | def _to_list(obj):
'''
Convert snetinfo object to list
'''
ret = {}
for attr in __attrs:
if hasattr(obj, attr):
ret[attr] = getattr(obj, attr)
return ret | [
"def",
"_to_list",
"(",
"obj",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"attr",
"in",
"__attrs",
":",
"if",
"hasattr",
"(",
"obj",
",",
"attr",
")",
":",
"ret",
"[",
"attr",
"]",
"=",
"getattr",
"(",
"obj",
",",
"attr",
")",
"return",
"ret"
] | Convert snetinfo object to list | [
"Convert",
"snetinfo",
"object",
"to",
"list"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/network_info.py#L33-L42 | train |
saltstack/salt | salt/beacons/network_info.py | validate | def validate(config):
'''
Validate the beacon configuration
'''
VALID_ITEMS = [
'type', 'bytes_sent', 'bytes_recv', 'packets_sent',
'packets_recv', 'errin', 'errout', 'dropin',
'dropout'
]
# Configuration for load beacon should be a list of dicts
if not isinstance(config, list):
return False, ('Configuration for network_info beacon must be a list.')
else:
_config = {}
list(map(_config.update, config))
for item in _config.get('interfaces', {}):
if not isinstance(_config['interfaces'][item], dict):
return False, ('Configuration for network_info beacon must '
'be a list of dictionaries.')
else:
if not any(j in VALID_ITEMS for j in _config['interfaces'][item]):
return False, ('Invalid configuration item in '
'Beacon configuration.')
return True, 'Valid beacon configuration' | python | def validate(config):
'''
Validate the beacon configuration
'''
VALID_ITEMS = [
'type', 'bytes_sent', 'bytes_recv', 'packets_sent',
'packets_recv', 'errin', 'errout', 'dropin',
'dropout'
]
# Configuration for load beacon should be a list of dicts
if not isinstance(config, list):
return False, ('Configuration for network_info beacon must be a list.')
else:
_config = {}
list(map(_config.update, config))
for item in _config.get('interfaces', {}):
if not isinstance(_config['interfaces'][item], dict):
return False, ('Configuration for network_info beacon must '
'be a list of dictionaries.')
else:
if not any(j in VALID_ITEMS for j in _config['interfaces'][item]):
return False, ('Invalid configuration item in '
'Beacon configuration.')
return True, 'Valid beacon configuration' | [
"def",
"validate",
"(",
"config",
")",
":",
"VALID_ITEMS",
"=",
"[",
"'type'",
",",
"'bytes_sent'",
",",
"'bytes_recv'",
",",
"'packets_sent'",
",",
"'packets_recv'",
",",
"'errin'",
",",
"'errout'",
",",
"'dropin'",
",",
"'dropout'",
"]",
"# Configuration for l... | Validate the beacon configuration | [
"Validate",
"the",
"beacon",
"configuration"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/network_info.py#L51-L78 | train |
saltstack/salt | salt/beacons/network_info.py | beacon | def beacon(config):
'''
Emit the network statistics of this host.
Specify thresholds for each network stat
and only emit a beacon if any of them are
exceeded.
Emit beacon when any values are equal to
configured values.
.. code-block:: yaml
beacons:
network_info:
- interfaces:
eth0:
type: equal
bytes_sent: 100000
bytes_recv: 100000
packets_sent: 100000
packets_recv: 100000
errin: 100
errout: 100
dropin: 100
dropout: 100
Emit beacon when any values are greater
than configured values.
.. code-block:: yaml
beacons:
network_info:
- interfaces:
eth0:
type: greater
bytes_sent: 100000
bytes_recv: 100000
packets_sent: 100000
packets_recv: 100000
errin: 100
errout: 100
dropin: 100
dropout: 100
'''
ret = []
_config = {}
list(map(_config.update, config))
log.debug('psutil.net_io_counters %s', psutil.net_io_counters)
_stats = psutil.net_io_counters(pernic=True)
log.debug('_stats %s', _stats)
for interface in _config.get('interfaces', {}):
if interface in _stats:
interface_config = _config['interfaces'][interface]
_if_stats = _stats[interface]
_diff = False
for attr in __attrs:
if attr in interface_config:
if 'type' in interface_config and \
interface_config['type'] == 'equal':
if getattr(_if_stats, attr, None) == \
int(interface_config[attr]):
_diff = True
elif 'type' in interface_config and \
interface_config['type'] == 'greater':
if getattr(_if_stats, attr, None) > \
int(interface_config[attr]):
_diff = True
else:
log.debug('attr %s', getattr(_if_stats,
attr, None))
else:
if getattr(_if_stats, attr, None) == \
int(interface_config[attr]):
_diff = True
if _diff:
ret.append({'interface': interface,
'network_info': _to_list(_if_stats)})
return ret | python | def beacon(config):
'''
Emit the network statistics of this host.
Specify thresholds for each network stat
and only emit a beacon if any of them are
exceeded.
Emit beacon when any values are equal to
configured values.
.. code-block:: yaml
beacons:
network_info:
- interfaces:
eth0:
type: equal
bytes_sent: 100000
bytes_recv: 100000
packets_sent: 100000
packets_recv: 100000
errin: 100
errout: 100
dropin: 100
dropout: 100
Emit beacon when any values are greater
than configured values.
.. code-block:: yaml
beacons:
network_info:
- interfaces:
eth0:
type: greater
bytes_sent: 100000
bytes_recv: 100000
packets_sent: 100000
packets_recv: 100000
errin: 100
errout: 100
dropin: 100
dropout: 100
'''
ret = []
_config = {}
list(map(_config.update, config))
log.debug('psutil.net_io_counters %s', psutil.net_io_counters)
_stats = psutil.net_io_counters(pernic=True)
log.debug('_stats %s', _stats)
for interface in _config.get('interfaces', {}):
if interface in _stats:
interface_config = _config['interfaces'][interface]
_if_stats = _stats[interface]
_diff = False
for attr in __attrs:
if attr in interface_config:
if 'type' in interface_config and \
interface_config['type'] == 'equal':
if getattr(_if_stats, attr, None) == \
int(interface_config[attr]):
_diff = True
elif 'type' in interface_config and \
interface_config['type'] == 'greater':
if getattr(_if_stats, attr, None) > \
int(interface_config[attr]):
_diff = True
else:
log.debug('attr %s', getattr(_if_stats,
attr, None))
else:
if getattr(_if_stats, attr, None) == \
int(interface_config[attr]):
_diff = True
if _diff:
ret.append({'interface': interface,
'network_info': _to_list(_if_stats)})
return ret | [
"def",
"beacon",
"(",
"config",
")",
":",
"ret",
"=",
"[",
"]",
"_config",
"=",
"{",
"}",
"list",
"(",
"map",
"(",
"_config",
".",
"update",
",",
"config",
")",
")",
"log",
".",
"debug",
"(",
"'psutil.net_io_counters %s'",
",",
"psutil",
".",
"net_io... | Emit the network statistics of this host.
Specify thresholds for each network stat
and only emit a beacon if any of them are
exceeded.
Emit beacon when any values are equal to
configured values.
.. code-block:: yaml
beacons:
network_info:
- interfaces:
eth0:
type: equal
bytes_sent: 100000
bytes_recv: 100000
packets_sent: 100000
packets_recv: 100000
errin: 100
errout: 100
dropin: 100
dropout: 100
Emit beacon when any values are greater
than configured values.
.. code-block:: yaml
beacons:
network_info:
- interfaces:
eth0:
type: greater
bytes_sent: 100000
bytes_recv: 100000
packets_sent: 100000
packets_recv: 100000
errin: 100
errout: 100
dropin: 100
dropout: 100 | [
"Emit",
"the",
"network",
"statistics",
"of",
"this",
"host",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/network_info.py#L81-L166 | train |
saltstack/salt | salt/modules/apcups.py | status | def status():
'''
Return apcaccess output
CLI Example:
.. code-block:: bash
salt '*' apcups.status
'''
ret = {}
apcaccess = _check_apcaccess()
res = __salt__['cmd.run_all'](apcaccess)
retcode = res['retcode']
if retcode != 0:
ret['Error'] = 'Something with wrong executing apcaccess, is apcupsd running?'
return ret
for line in res['stdout'].splitlines():
line = line.split(':')
ret[line[0].strip()] = line[1].strip()
return ret | python | def status():
'''
Return apcaccess output
CLI Example:
.. code-block:: bash
salt '*' apcups.status
'''
ret = {}
apcaccess = _check_apcaccess()
res = __salt__['cmd.run_all'](apcaccess)
retcode = res['retcode']
if retcode != 0:
ret['Error'] = 'Something with wrong executing apcaccess, is apcupsd running?'
return ret
for line in res['stdout'].splitlines():
line = line.split(':')
ret[line[0].strip()] = line[1].strip()
return ret | [
"def",
"status",
"(",
")",
":",
"ret",
"=",
"{",
"}",
"apcaccess",
"=",
"_check_apcaccess",
"(",
")",
"res",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"apcaccess",
")",
"retcode",
"=",
"res",
"[",
"'retcode'",
"]",
"if",
"retcode",
"!=",
"0",
... | Return apcaccess output
CLI Example:
.. code-block:: bash
salt '*' apcups.status | [
"Return",
"apcaccess",
"output"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apcups.py#L42-L64 | train |
saltstack/salt | salt/modules/apcups.py | status_load | def status_load():
'''
Return load
CLI Example:
.. code-block:: bash
salt '*' apcups.status_load
'''
data = status()
if 'LOADPCT' in data:
load = data['LOADPCT'].split()
if load[1].lower() == 'percent':
return float(load[0])
return {'Error': 'Load not available.'} | python | def status_load():
'''
Return load
CLI Example:
.. code-block:: bash
salt '*' apcups.status_load
'''
data = status()
if 'LOADPCT' in data:
load = data['LOADPCT'].split()
if load[1].lower() == 'percent':
return float(load[0])
return {'Error': 'Load not available.'} | [
"def",
"status_load",
"(",
")",
":",
"data",
"=",
"status",
"(",
")",
"if",
"'LOADPCT'",
"in",
"data",
":",
"load",
"=",
"data",
"[",
"'LOADPCT'",
"]",
".",
"split",
"(",
")",
"if",
"load",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"==",
"'percent'"... | Return load
CLI Example:
.. code-block:: bash
salt '*' apcups.status_load | [
"Return",
"load"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apcups.py#L67-L83 | train |
saltstack/salt | salt/modules/apcups.py | status_charge | def status_charge():
'''
Return battery charge
CLI Example:
.. code-block:: bash
salt '*' apcups.status_charge
'''
data = status()
if 'BCHARGE' in data:
charge = data['BCHARGE'].split()
if charge[1].lower() == 'percent':
return float(charge[0])
return {'Error': 'Load not available.'} | python | def status_charge():
'''
Return battery charge
CLI Example:
.. code-block:: bash
salt '*' apcups.status_charge
'''
data = status()
if 'BCHARGE' in data:
charge = data['BCHARGE'].split()
if charge[1].lower() == 'percent':
return float(charge[0])
return {'Error': 'Load not available.'} | [
"def",
"status_charge",
"(",
")",
":",
"data",
"=",
"status",
"(",
")",
"if",
"'BCHARGE'",
"in",
"data",
":",
"charge",
"=",
"data",
"[",
"'BCHARGE'",
"]",
".",
"split",
"(",
")",
"if",
"charge",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"==",
"'per... | Return battery charge
CLI Example:
.. code-block:: bash
salt '*' apcups.status_charge | [
"Return",
"battery",
"charge"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apcups.py#L86-L102 | train |
saltstack/salt | salt/states/esxi.py | coredump_configured | def coredump_configured(name, enabled, dump_ip, host_vnic='vmk0', dump_port=6500):
'''
Ensures a host's core dump configuration.
name
Name of the state.
enabled
Sets whether or not ESXi core dump collection should be enabled.
This is a boolean value set to ``True`` or ``False`` to enable
or disable core dumps.
Note that ESXi requires that the core dump must be enabled before
any other parameters may be set. This also affects the ``changes``
results in the state return dictionary. If ``enabled`` is ``False``,
we can't obtain any previous settings to compare other state variables,
resulting in many ``old`` references returning ``None``.
Once ``enabled`` is ``True`` the ``changes`` dictionary comparisons
will be more accurate. This is due to the way the system coredemp
network configuration command returns data.
dump_ip
The IP address of host that will accept the dump.
host_vnic
Host VNic port through which to communicate. Defaults to ``vmk0``.
dump_port
TCP port to use for the dump. Defaults to ``6500``.
Example:
.. code-block:: yaml
configure-host-coredump:
esxi.coredump_configured:
- enabled: True
- dump_ip: 'my-coredump-ip.example.com'
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
esxi_cmd = 'esxi.cmd'
enabled_msg = 'ESXi requires that the core dump must be enabled ' \
'before any other parameters may be set.'
host = __pillar__['proxy']['host']
current_config = __salt__[esxi_cmd]('get_coredump_network_config').get(host)
error = current_config.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
current_config = current_config.get('Coredump Config')
current_enabled = current_config.get('enabled')
# Configure coredump enabled state, if there are changes.
if current_enabled != enabled:
enabled_changes = {'enabled': {'old': current_enabled, 'new': enabled}}
# Only run the command if not using test=True
if not __opts__['test']:
response = __salt__[esxi_cmd]('coredump_network_enable',
enabled=enabled).get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
# Allow users to disable core dump, but then return since
# nothing else can be set if core dump is disabled.
if not enabled:
ret['result'] = True
ret['comment'] = enabled_msg
ret['changes'].update(enabled_changes)
return ret
ret['changes'].update(enabled_changes)
elif not enabled:
# If current_enabled and enabled match, but are both False,
# We must return before configuring anything. This isn't a
# failure as core dump may be disabled intentionally.
ret['result'] = True
ret['comment'] = enabled_msg
return ret
# Test for changes with all remaining configurations. The changes flag is used
# To detect changes, and then set_coredump_network_config is called one time.
changes = False
current_ip = current_config.get('ip')
if current_ip != dump_ip:
ret['changes'].update({'dump_ip':
{'old': current_ip,
'new': dump_ip}})
changes = True
current_vnic = current_config.get('host_vnic')
if current_vnic != host_vnic:
ret['changes'].update({'host_vnic':
{'old': current_vnic,
'new': host_vnic}})
changes = True
current_port = current_config.get('port')
if current_port != six.text_type(dump_port):
ret['changes'].update({'dump_port':
{'old': current_port,
'new': six.text_type(dump_port)}})
changes = True
# Only run the command if not using test=True and changes were detected.
if not __opts__['test'] and changes is True:
response = __salt__[esxi_cmd]('set_coredump_network_config',
dump_ip=dump_ip,
host_vnic=host_vnic,
dump_port=dump_port).get(host)
if response.get('success') is False:
msg = response.get('stderr')
if not msg:
msg = response.get('stdout')
ret['comment'] = 'Error: {0}'.format(msg)
return ret
ret['result'] = True
if ret['changes'] == {}:
ret['comment'] = 'Core Dump configuration is already in the desired state.'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Core dump configuration will change.'
return ret | python | def coredump_configured(name, enabled, dump_ip, host_vnic='vmk0', dump_port=6500):
'''
Ensures a host's core dump configuration.
name
Name of the state.
enabled
Sets whether or not ESXi core dump collection should be enabled.
This is a boolean value set to ``True`` or ``False`` to enable
or disable core dumps.
Note that ESXi requires that the core dump must be enabled before
any other parameters may be set. This also affects the ``changes``
results in the state return dictionary. If ``enabled`` is ``False``,
we can't obtain any previous settings to compare other state variables,
resulting in many ``old`` references returning ``None``.
Once ``enabled`` is ``True`` the ``changes`` dictionary comparisons
will be more accurate. This is due to the way the system coredemp
network configuration command returns data.
dump_ip
The IP address of host that will accept the dump.
host_vnic
Host VNic port through which to communicate. Defaults to ``vmk0``.
dump_port
TCP port to use for the dump. Defaults to ``6500``.
Example:
.. code-block:: yaml
configure-host-coredump:
esxi.coredump_configured:
- enabled: True
- dump_ip: 'my-coredump-ip.example.com'
'''
ret = {'name': name,
'result': False,
'changes': {},
'comment': ''}
esxi_cmd = 'esxi.cmd'
enabled_msg = 'ESXi requires that the core dump must be enabled ' \
'before any other parameters may be set.'
host = __pillar__['proxy']['host']
current_config = __salt__[esxi_cmd]('get_coredump_network_config').get(host)
error = current_config.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
current_config = current_config.get('Coredump Config')
current_enabled = current_config.get('enabled')
# Configure coredump enabled state, if there are changes.
if current_enabled != enabled:
enabled_changes = {'enabled': {'old': current_enabled, 'new': enabled}}
# Only run the command if not using test=True
if not __opts__['test']:
response = __salt__[esxi_cmd]('coredump_network_enable',
enabled=enabled).get(host)
error = response.get('Error')
if error:
ret['comment'] = 'Error: {0}'.format(error)
return ret
# Allow users to disable core dump, but then return since
# nothing else can be set if core dump is disabled.
if not enabled:
ret['result'] = True
ret['comment'] = enabled_msg
ret['changes'].update(enabled_changes)
return ret
ret['changes'].update(enabled_changes)
elif not enabled:
# If current_enabled and enabled match, but are both False,
# We must return before configuring anything. This isn't a
# failure as core dump may be disabled intentionally.
ret['result'] = True
ret['comment'] = enabled_msg
return ret
# Test for changes with all remaining configurations. The changes flag is used
# To detect changes, and then set_coredump_network_config is called one time.
changes = False
current_ip = current_config.get('ip')
if current_ip != dump_ip:
ret['changes'].update({'dump_ip':
{'old': current_ip,
'new': dump_ip}})
changes = True
current_vnic = current_config.get('host_vnic')
if current_vnic != host_vnic:
ret['changes'].update({'host_vnic':
{'old': current_vnic,
'new': host_vnic}})
changes = True
current_port = current_config.get('port')
if current_port != six.text_type(dump_port):
ret['changes'].update({'dump_port':
{'old': current_port,
'new': six.text_type(dump_port)}})
changes = True
# Only run the command if not using test=True and changes were detected.
if not __opts__['test'] and changes is True:
response = __salt__[esxi_cmd]('set_coredump_network_config',
dump_ip=dump_ip,
host_vnic=host_vnic,
dump_port=dump_port).get(host)
if response.get('success') is False:
msg = response.get('stderr')
if not msg:
msg = response.get('stdout')
ret['comment'] = 'Error: {0}'.format(msg)
return ret
ret['result'] = True
if ret['changes'] == {}:
ret['comment'] = 'Core Dump configuration is already in the desired state.'
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Core dump configuration will change.'
return ret | [
"def",
"coredump_configured",
"(",
"name",
",",
"enabled",
",",
"dump_ip",
",",
"host_vnic",
"=",
"'vmk0'",
",",
"dump_port",
"=",
"6500",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"False",
",",
"'changes'",
":",
"{",
"}",... | Ensures a host's core dump configuration.
name
Name of the state.
enabled
Sets whether or not ESXi core dump collection should be enabled.
This is a boolean value set to ``True`` or ``False`` to enable
or disable core dumps.
Note that ESXi requires that the core dump must be enabled before
any other parameters may be set. This also affects the ``changes``
results in the state return dictionary. If ``enabled`` is ``False``,
we can't obtain any previous settings to compare other state variables,
resulting in many ``old`` references returning ``None``.
Once ``enabled`` is ``True`` the ``changes`` dictionary comparisons
will be more accurate. This is due to the way the system coredemp
network configuration command returns data.
dump_ip
The IP address of host that will accept the dump.
host_vnic
Host VNic port through which to communicate. Defaults to ``vmk0``.
dump_port
TCP port to use for the dump. Defaults to ``6500``.
Example:
.. code-block:: yaml
configure-host-coredump:
esxi.coredump_configured:
- enabled: True
- dump_ip: 'my-coredump-ip.example.com' | [
"Ensures",
"a",
"host",
"s",
"core",
"dump",
"configuration",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/esxi.py#L139-L274 | train |
saltstack/salt | salt/states/esxi.py | password_present | def password_present(name, password):
'''
Ensures the given password is set on the ESXi host. Passwords cannot be obtained from
host, so if a password is set in this state, the ``vsphere.update_host_password``
function will always run (except when using test=True functionality) and the state's
changes dictionary will always be populated.
The username for which the password will change is the same username that is used to
authenticate against the ESXi host via the Proxy Minion. For example, if the pillar
definition for the proxy username is defined as ``root``, then the username that the
password will be updated for via this state is ``root``.
name
Name of the state.
password
The new password to change on the host.
Example:
.. code-block:: yaml
configure-host-password:
esxi.password_present:
- password: 'new-bad-password'
'''
ret = {'name': name,
'result': True,
'changes': {'old': 'unknown',
'new': '********'},
'comment': 'Host password was updated.'}
esxi_cmd = 'esxi.cmd'
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Host password will change.'
return ret
else:
try:
__salt__[esxi_cmd]('update_host_password',
new_password=password)
except CommandExecutionError as err:
ret['result'] = False
ret['comment'] = 'Error: {0}'.format(err)
return ret
return ret | python | def password_present(name, password):
'''
Ensures the given password is set on the ESXi host. Passwords cannot be obtained from
host, so if a password is set in this state, the ``vsphere.update_host_password``
function will always run (except when using test=True functionality) and the state's
changes dictionary will always be populated.
The username for which the password will change is the same username that is used to
authenticate against the ESXi host via the Proxy Minion. For example, if the pillar
definition for the proxy username is defined as ``root``, then the username that the
password will be updated for via this state is ``root``.
name
Name of the state.
password
The new password to change on the host.
Example:
.. code-block:: yaml
configure-host-password:
esxi.password_present:
- password: 'new-bad-password'
'''
ret = {'name': name,
'result': True,
'changes': {'old': 'unknown',
'new': '********'},
'comment': 'Host password was updated.'}
esxi_cmd = 'esxi.cmd'
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Host password will change.'
return ret
else:
try:
__salt__[esxi_cmd]('update_host_password',
new_password=password)
except CommandExecutionError as err:
ret['result'] = False
ret['comment'] = 'Error: {0}'.format(err)
return ret
return ret | [
"def",
"password_present",
"(",
"name",
",",
"password",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'changes'",
":",
"{",
"'old'",
":",
"'unknown'",
",",
"'new'",
":",
"'********'",
"}",
",",
"'comment'",
":",... | Ensures the given password is set on the ESXi host. Passwords cannot be obtained from
host, so if a password is set in this state, the ``vsphere.update_host_password``
function will always run (except when using test=True functionality) and the state's
changes dictionary will always be populated.
The username for which the password will change is the same username that is used to
authenticate against the ESXi host via the Proxy Minion. For example, if the pillar
definition for the proxy username is defined as ``root``, then the username that the
password will be updated for via this state is ``root``.
name
Name of the state.
password
The new password to change on the host.
Example:
.. code-block:: yaml
configure-host-password:
esxi.password_present:
- password: 'new-bad-password' | [
"Ensures",
"the",
"given",
"password",
"is",
"set",
"on",
"the",
"ESXi",
"host",
".",
"Passwords",
"cannot",
"be",
"obtained",
"from",
"host",
"so",
"if",
"a",
"password",
"is",
"set",
"in",
"this",
"state",
"the",
"vsphere",
".",
"update_host_password",
"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/esxi.py#L277-L323 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.