repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
saltstack/salt | salt/utils/listdiffer.py | ListDictDiffer.changes_str | def changes_str(self):
'''Returns a string describing the changes'''
changes = ''
for item in self._get_recursive_difference(type='intersect'):
if item.diffs:
changes = ''.join([changes,
# Tabulate comment deeper, show the key attribute and the value
# Next line should be tabulated even deeper,
# every change should be tabulated 1 deeper
'\tidentified by {0} {1}:\n\t{2}\n'.format(
self._key,
item.past_dict[self._key],
item.changes_str.replace('\n', '\n\t'))])
for item in self._get_recursive_difference(type='removed'):
if item.past_dict:
changes = ''.join([changes,
# Tabulate comment deeper, show the key attribute and the value
'\tidentified by {0} {1}:'
'\n\twill be removed\n'.format(self._key,
item.past_dict[self._key])])
for item in self._get_recursive_difference(type='added'):
if item.current_dict:
changes = ''.join([changes,
# Tabulate comment deeper, show the key attribute and the value
'\tidentified by {0} {1}:'
'\n\twill be added\n'.format(self._key,
item.current_dict[self._key])])
return changes | python | def changes_str(self):
'''Returns a string describing the changes'''
changes = ''
for item in self._get_recursive_difference(type='intersect'):
if item.diffs:
changes = ''.join([changes,
# Tabulate comment deeper, show the key attribute and the value
# Next line should be tabulated even deeper,
# every change should be tabulated 1 deeper
'\tidentified by {0} {1}:\n\t{2}\n'.format(
self._key,
item.past_dict[self._key],
item.changes_str.replace('\n', '\n\t'))])
for item in self._get_recursive_difference(type='removed'):
if item.past_dict:
changes = ''.join([changes,
# Tabulate comment deeper, show the key attribute and the value
'\tidentified by {0} {1}:'
'\n\twill be removed\n'.format(self._key,
item.past_dict[self._key])])
for item in self._get_recursive_difference(type='added'):
if item.current_dict:
changes = ''.join([changes,
# Tabulate comment deeper, show the key attribute and the value
'\tidentified by {0} {1}:'
'\n\twill be added\n'.format(self._key,
item.current_dict[self._key])])
return changes | [
"def",
"changes_str",
"(",
"self",
")",
":",
"changes",
"=",
"''",
"for",
"item",
"in",
"self",
".",
"_get_recursive_difference",
"(",
"type",
"=",
"'intersect'",
")",
":",
"if",
"item",
".",
"diffs",
":",
"changes",
"=",
"''",
".",
"join",
"(",
"[",
... | Returns a string describing the changes | [
"Returns",
"a",
"string",
"describing",
"the",
"changes"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/listdiffer.py#L131-L158 | train |
saltstack/salt | salt/utils/listdiffer.py | ListDictDiffer.changes_str2 | def changes_str2(self, tab_string=' '):
'''
Returns a string in a more compact format describing the changes.
The output better alligns with the one in recursive_diff.
'''
changes = []
for item in self._get_recursive_difference(type='intersect'):
if item.diffs:
changes.append('{tab}{0}={1} (updated):\n{tab}{tab}{2}'
''.format(self._key, item.past_dict[self._key],
item.changes_str.replace(
'\n',
'\n{0}{0}'.format(tab_string)),
tab=tab_string))
for item in self._get_recursive_difference(type='removed'):
if item.past_dict:
changes.append('{tab}{0}={1} (removed)'.format(
self._key, item.past_dict[self._key], tab=tab_string))
for item in self._get_recursive_difference(type='added'):
if item.current_dict:
changes.append('{tab}{0}={1} (added): {2}'.format(
self._key, item.current_dict[self._key],
dict(item.current_dict), tab=tab_string))
return '\n'.join(changes) | python | def changes_str2(self, tab_string=' '):
'''
Returns a string in a more compact format describing the changes.
The output better alligns with the one in recursive_diff.
'''
changes = []
for item in self._get_recursive_difference(type='intersect'):
if item.diffs:
changes.append('{tab}{0}={1} (updated):\n{tab}{tab}{2}'
''.format(self._key, item.past_dict[self._key],
item.changes_str.replace(
'\n',
'\n{0}{0}'.format(tab_string)),
tab=tab_string))
for item in self._get_recursive_difference(type='removed'):
if item.past_dict:
changes.append('{tab}{0}={1} (removed)'.format(
self._key, item.past_dict[self._key], tab=tab_string))
for item in self._get_recursive_difference(type='added'):
if item.current_dict:
changes.append('{tab}{0}={1} (added): {2}'.format(
self._key, item.current_dict[self._key],
dict(item.current_dict), tab=tab_string))
return '\n'.join(changes) | [
"def",
"changes_str2",
"(",
"self",
",",
"tab_string",
"=",
"' '",
")",
":",
"changes",
"=",
"[",
"]",
"for",
"item",
"in",
"self",
".",
"_get_recursive_difference",
"(",
"type",
"=",
"'intersect'",
")",
":",
"if",
"item",
".",
"diffs",
":",
"changes",
... | Returns a string in a more compact format describing the changes.
The output better alligns with the one in recursive_diff. | [
"Returns",
"a",
"string",
"in",
"a",
"more",
"compact",
"format",
"describing",
"the",
"changes",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/listdiffer.py#L161-L185 | train |
saltstack/salt | salt/utils/listdiffer.py | ListDictDiffer.new_values | def new_values(self):
'''Returns the new values from the diff'''
def get_new_values_and_key(item):
values = item.new_values
if item.past_dict:
values.update({self._key: item.past_dict[self._key]})
else:
# This is a new item as it has no past_dict
values.update({self._key: item.current_dict[self._key]})
return values
return [get_new_values_and_key(el)
for el in self._get_recursive_difference('all')
if el.diffs and el.current_dict] | python | def new_values(self):
'''Returns the new values from the diff'''
def get_new_values_and_key(item):
values = item.new_values
if item.past_dict:
values.update({self._key: item.past_dict[self._key]})
else:
# This is a new item as it has no past_dict
values.update({self._key: item.current_dict[self._key]})
return values
return [get_new_values_and_key(el)
for el in self._get_recursive_difference('all')
if el.diffs and el.current_dict] | [
"def",
"new_values",
"(",
"self",
")",
":",
"def",
"get_new_values_and_key",
"(",
"item",
")",
":",
"values",
"=",
"item",
".",
"new_values",
"if",
"item",
".",
"past_dict",
":",
"values",
".",
"update",
"(",
"{",
"self",
".",
"_key",
":",
"item",
".",... | Returns the new values from the diff | [
"Returns",
"the",
"new",
"values",
"from",
"the",
"diff"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/listdiffer.py#L188-L201 | train |
saltstack/salt | salt/utils/listdiffer.py | ListDictDiffer.old_values | def old_values(self):
'''Returns the old values from the diff'''
def get_old_values_and_key(item):
values = item.old_values
values.update({self._key: item.past_dict[self._key]})
return values
return [get_old_values_and_key(el)
for el in self._get_recursive_difference('all')
if el.diffs and el.past_dict] | python | def old_values(self):
'''Returns the old values from the diff'''
def get_old_values_and_key(item):
values = item.old_values
values.update({self._key: item.past_dict[self._key]})
return values
return [get_old_values_and_key(el)
for el in self._get_recursive_difference('all')
if el.diffs and el.past_dict] | [
"def",
"old_values",
"(",
"self",
")",
":",
"def",
"get_old_values_and_key",
"(",
"item",
")",
":",
"values",
"=",
"item",
".",
"old_values",
"values",
".",
"update",
"(",
"{",
"self",
".",
"_key",
":",
"item",
".",
"past_dict",
"[",
"self",
".",
"_key... | Returns the old values from the diff | [
"Returns",
"the",
"old",
"values",
"from",
"the",
"diff"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/listdiffer.py#L204-L213 | train |
saltstack/salt | salt/utils/listdiffer.py | ListDictDiffer.changed | def changed(self, selection='all'):
'''
Returns the list of changed values.
The key is added to each item.
selection
Specifies the desired changes.
Supported values are
``all`` - all changed items are included in the output
``intersect`` - changed items present in both lists are included
'''
changed = []
if selection == 'all':
for recursive_item in self._get_recursive_difference(type='all'):
# We want the unset values as well
recursive_item.ignore_unset_values = False
key_val = six.text_type(recursive_item.past_dict[self._key]) \
if self._key in recursive_item.past_dict \
else six.text_type(recursive_item.current_dict[self._key])
for change in recursive_item.changed():
if change != self._key:
changed.append('.'.join([self._key, key_val, change]))
return changed
elif selection == 'intersect':
# We want the unset values as well
for recursive_item in self._get_recursive_difference(type='intersect'):
recursive_item.ignore_unset_values = False
key_val = six.text_type(recursive_item.past_dict[self._key]) \
if self._key in recursive_item.past_dict \
else six.text_type(recursive_item.current_dict[self._key])
for change in recursive_item.changed():
if change != self._key:
changed.append('.'.join([self._key, key_val, change]))
return changed | python | def changed(self, selection='all'):
'''
Returns the list of changed values.
The key is added to each item.
selection
Specifies the desired changes.
Supported values are
``all`` - all changed items are included in the output
``intersect`` - changed items present in both lists are included
'''
changed = []
if selection == 'all':
for recursive_item in self._get_recursive_difference(type='all'):
# We want the unset values as well
recursive_item.ignore_unset_values = False
key_val = six.text_type(recursive_item.past_dict[self._key]) \
if self._key in recursive_item.past_dict \
else six.text_type(recursive_item.current_dict[self._key])
for change in recursive_item.changed():
if change != self._key:
changed.append('.'.join([self._key, key_val, change]))
return changed
elif selection == 'intersect':
# We want the unset values as well
for recursive_item in self._get_recursive_difference(type='intersect'):
recursive_item.ignore_unset_values = False
key_val = six.text_type(recursive_item.past_dict[self._key]) \
if self._key in recursive_item.past_dict \
else six.text_type(recursive_item.current_dict[self._key])
for change in recursive_item.changed():
if change != self._key:
changed.append('.'.join([self._key, key_val, change]))
return changed | [
"def",
"changed",
"(",
"self",
",",
"selection",
"=",
"'all'",
")",
":",
"changed",
"=",
"[",
"]",
"if",
"selection",
"==",
"'all'",
":",
"for",
"recursive_item",
"in",
"self",
".",
"_get_recursive_difference",
"(",
"type",
"=",
"'all'",
")",
":",
"# We ... | Returns the list of changed values.
The key is added to each item.
selection
Specifies the desired changes.
Supported values are
``all`` - all changed items are included in the output
``intersect`` - changed items present in both lists are included | [
"Returns",
"the",
"list",
"of",
"changed",
"values",
".",
"The",
"key",
"is",
"added",
"to",
"each",
"item",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/listdiffer.py#L215-L250 | train |
saltstack/salt | salt/runners/salt.py | cmd | def cmd(fun, *args, **kwargs):
'''
.. versionchanged:: 2018.3.0
Added ``with_pillar`` argument
Execute ``fun`` with the given ``args`` and ``kwargs``. Parameter ``fun``
should be the string :ref:`name <all-salt.modules>` of the execution module
to call.
.. note::
Execution modules will be loaded *every time* this function is called.
Additionally, keep in mind that since runners execute on the master,
custom execution modules will need to be synced to the master using
:py:func:`salt-run saltutil.sync_modules
<salt.runners.saltutil.sync_modules>`, otherwise they will not be
available.
with_pillar : False
If ``True``, pillar data will be compiled for the master
.. note::
To target the master in the pillar top file, keep in mind that the
default ``id`` for the master is ``<hostname>_master``. This can be
overridden by setting an ``id`` configuration parameter in the
master config file.
CLI example:
.. code-block:: bash
salt-run salt.cmd test.ping
# call functions with arguments and keyword arguments
salt-run salt.cmd test.arg 1 2 3 a=1
salt-run salt.cmd mymod.myfunc with_pillar=True
'''
log.debug('Called salt.cmd runner with minion function %s', fun)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
with_pillar = kwargs.pop('with_pillar', False)
opts = copy.deepcopy(__opts__)
# try to only load grains if we need to, it may already exist from other contexts (e.g., pillar)
if 'grains' not in opts:
_, grains, _ = salt.utils.minions.get_minion_data(__opts__['id'], __opts__)
if grains:
opts['grains'] = grains
else:
opts['grains'] = salt.loader.grains(opts)
if with_pillar:
opts['pillar'] = salt.pillar.get_pillar(
opts,
opts['grains'],
opts['id'],
saltenv=opts['saltenv'],
pillarenv=opts.get('pillarenv')).compile_pillar()
else:
opts['pillar'] = {}
functions = salt.loader.minion_mods(
opts,
utils=salt.loader.utils(opts),
context=__context__)
return functions[fun](*args, **kwargs) \
if fun in functions \
else '\'{0}\' is not available.'.format(fun) | python | def cmd(fun, *args, **kwargs):
'''
.. versionchanged:: 2018.3.0
Added ``with_pillar`` argument
Execute ``fun`` with the given ``args`` and ``kwargs``. Parameter ``fun``
should be the string :ref:`name <all-salt.modules>` of the execution module
to call.
.. note::
Execution modules will be loaded *every time* this function is called.
Additionally, keep in mind that since runners execute on the master,
custom execution modules will need to be synced to the master using
:py:func:`salt-run saltutil.sync_modules
<salt.runners.saltutil.sync_modules>`, otherwise they will not be
available.
with_pillar : False
If ``True``, pillar data will be compiled for the master
.. note::
To target the master in the pillar top file, keep in mind that the
default ``id`` for the master is ``<hostname>_master``. This can be
overridden by setting an ``id`` configuration parameter in the
master config file.
CLI example:
.. code-block:: bash
salt-run salt.cmd test.ping
# call functions with arguments and keyword arguments
salt-run salt.cmd test.arg 1 2 3 a=1
salt-run salt.cmd mymod.myfunc with_pillar=True
'''
log.debug('Called salt.cmd runner with minion function %s', fun)
kwargs = salt.utils.args.clean_kwargs(**kwargs)
with_pillar = kwargs.pop('with_pillar', False)
opts = copy.deepcopy(__opts__)
# try to only load grains if we need to, it may already exist from other contexts (e.g., pillar)
if 'grains' not in opts:
_, grains, _ = salt.utils.minions.get_minion_data(__opts__['id'], __opts__)
if grains:
opts['grains'] = grains
else:
opts['grains'] = salt.loader.grains(opts)
if with_pillar:
opts['pillar'] = salt.pillar.get_pillar(
opts,
opts['grains'],
opts['id'],
saltenv=opts['saltenv'],
pillarenv=opts.get('pillarenv')).compile_pillar()
else:
opts['pillar'] = {}
functions = salt.loader.minion_mods(
opts,
utils=salt.loader.utils(opts),
context=__context__)
return functions[fun](*args, **kwargs) \
if fun in functions \
else '\'{0}\' is not available.'.format(fun) | [
"def",
"cmd",
"(",
"fun",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
".",
"debug",
"(",
"'Called salt.cmd runner with minion function %s'",
",",
"fun",
")",
"kwargs",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"clean_kwargs",
"(",
"*",... | .. versionchanged:: 2018.3.0
Added ``with_pillar`` argument
Execute ``fun`` with the given ``args`` and ``kwargs``. Parameter ``fun``
should be the string :ref:`name <all-salt.modules>` of the execution module
to call.
.. note::
Execution modules will be loaded *every time* this function is called.
Additionally, keep in mind that since runners execute on the master,
custom execution modules will need to be synced to the master using
:py:func:`salt-run saltutil.sync_modules
<salt.runners.saltutil.sync_modules>`, otherwise they will not be
available.
with_pillar : False
If ``True``, pillar data will be compiled for the master
.. note::
To target the master in the pillar top file, keep in mind that the
default ``id`` for the master is ``<hostname>_master``. This can be
overridden by setting an ``id`` configuration parameter in the
master config file.
CLI example:
.. code-block:: bash
salt-run salt.cmd test.ping
# call functions with arguments and keyword arguments
salt-run salt.cmd test.arg 1 2 3 a=1
salt-run salt.cmd mymod.myfunc with_pillar=True | [
"..",
"versionchanged",
"::",
"2018",
".",
"3",
".",
"0",
"Added",
"with_pillar",
"argument"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/salt.py#L48-L114 | train |
saltstack/salt | salt/runners/salt.py | execute | def execute(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
jid='',
kwarg=None,
**kwargs):
'''
.. versionadded:: 2017.7.0
Execute ``fun`` on all minions matched by ``tgt`` and ``tgt_type``.
Parameter ``fun`` is the name of execution module function to call.
This function should mainly be used as a helper for runner modules,
in order to avoid redundant code.
For example, when inside a runner one needs to execute a certain function
on arbitrary groups of minions, only has to:
.. code-block:: python
ret1 = __salt__['salt.execute']('*', 'mod.fun')
ret2 = __salt__['salt.execute']('my_nodegroup', 'mod2.fun2', tgt_type='nodegroup')
It can also be used to schedule jobs directly on the master, for example:
.. code-block:: yaml
schedule:
collect_bgp_stats:
function: salt.execute
args:
- edge-routers
- bgp.neighbors
kwargs:
tgt_type: nodegroup
days: 1
returner: redis
'''
client = salt.client.get_local_client(__opts__['conf_file'])
try:
ret = client.cmd(tgt,
fun,
arg=arg,
timeout=timeout or __opts__['timeout'],
tgt_type=tgt_type, # no warn_until, as this is introduced only in 2017.7.0
ret=ret,
jid=jid,
kwarg=kwarg,
**kwargs)
except SaltClientError as client_error:
log.error('Error while executing %s on %s (%s)', fun, tgt, tgt_type)
log.error(client_error)
return {}
return ret | python | def execute(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
jid='',
kwarg=None,
**kwargs):
'''
.. versionadded:: 2017.7.0
Execute ``fun`` on all minions matched by ``tgt`` and ``tgt_type``.
Parameter ``fun`` is the name of execution module function to call.
This function should mainly be used as a helper for runner modules,
in order to avoid redundant code.
For example, when inside a runner one needs to execute a certain function
on arbitrary groups of minions, only has to:
.. code-block:: python
ret1 = __salt__['salt.execute']('*', 'mod.fun')
ret2 = __salt__['salt.execute']('my_nodegroup', 'mod2.fun2', tgt_type='nodegroup')
It can also be used to schedule jobs directly on the master, for example:
.. code-block:: yaml
schedule:
collect_bgp_stats:
function: salt.execute
args:
- edge-routers
- bgp.neighbors
kwargs:
tgt_type: nodegroup
days: 1
returner: redis
'''
client = salt.client.get_local_client(__opts__['conf_file'])
try:
ret = client.cmd(tgt,
fun,
arg=arg,
timeout=timeout or __opts__['timeout'],
tgt_type=tgt_type, # no warn_until, as this is introduced only in 2017.7.0
ret=ret,
jid=jid,
kwarg=kwarg,
**kwargs)
except SaltClientError as client_error:
log.error('Error while executing %s on %s (%s)', fun, tgt, tgt_type)
log.error(client_error)
return {}
return ret | [
"def",
"execute",
"(",
"tgt",
",",
"fun",
",",
"arg",
"=",
"(",
")",
",",
"timeout",
"=",
"None",
",",
"tgt_type",
"=",
"'glob'",
",",
"ret",
"=",
"''",
",",
"jid",
"=",
"''",
",",
"kwarg",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"cli... | .. versionadded:: 2017.7.0
Execute ``fun`` on all minions matched by ``tgt`` and ``tgt_type``.
Parameter ``fun`` is the name of execution module function to call.
This function should mainly be used as a helper for runner modules,
in order to avoid redundant code.
For example, when inside a runner one needs to execute a certain function
on arbitrary groups of minions, only has to:
.. code-block:: python
ret1 = __salt__['salt.execute']('*', 'mod.fun')
ret2 = __salt__['salt.execute']('my_nodegroup', 'mod2.fun2', tgt_type='nodegroup')
It can also be used to schedule jobs directly on the master, for example:
.. code-block:: yaml
schedule:
collect_bgp_stats:
function: salt.execute
args:
- edge-routers
- bgp.neighbors
kwargs:
tgt_type: nodegroup
days: 1
returner: redis | [
"..",
"versionadded",
"::",
"2017",
".",
"7",
".",
"0"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/salt.py#L117-L172 | train |
saltstack/salt | salt/modules/win_file.py | _resolve_symlink | def _resolve_symlink(path, max_depth=64):
'''
Resolves the given symlink path to its real path, up to a maximum of the
`max_depth` parameter which defaults to 64.
If the path is not a symlink path, it is simply returned.
'''
if sys.getwindowsversion().major < 6:
raise SaltInvocationError('Symlinks are only supported on Windows Vista or later.')
# make sure we don't get stuck in a symlink loop!
paths_seen = set((path, ))
cur_depth = 0
while is_link(path):
path = readlink(path)
if path in paths_seen:
raise CommandExecutionError('The given path is involved in a symlink loop.')
paths_seen.add(path)
cur_depth += 1
if cur_depth > max_depth:
raise CommandExecutionError('Too many levels of symbolic links.')
return path | python | def _resolve_symlink(path, max_depth=64):
'''
Resolves the given symlink path to its real path, up to a maximum of the
`max_depth` parameter which defaults to 64.
If the path is not a symlink path, it is simply returned.
'''
if sys.getwindowsversion().major < 6:
raise SaltInvocationError('Symlinks are only supported on Windows Vista or later.')
# make sure we don't get stuck in a symlink loop!
paths_seen = set((path, ))
cur_depth = 0
while is_link(path):
path = readlink(path)
if path in paths_seen:
raise CommandExecutionError('The given path is involved in a symlink loop.')
paths_seen.add(path)
cur_depth += 1
if cur_depth > max_depth:
raise CommandExecutionError('Too many levels of symbolic links.')
return path | [
"def",
"_resolve_symlink",
"(",
"path",
",",
"max_depth",
"=",
"64",
")",
":",
"if",
"sys",
".",
"getwindowsversion",
"(",
")",
".",
"major",
"<",
"6",
":",
"raise",
"SaltInvocationError",
"(",
"'Symlinks are only supported on Windows Vista or later.'",
")",
"# ma... | Resolves the given symlink path to its real path, up to a maximum of the
`max_depth` parameter which defaults to 64.
If the path is not a symlink path, it is simply returned. | [
"Resolves",
"the",
"given",
"symlink",
"path",
"to",
"its",
"real",
"path",
"up",
"to",
"a",
"maximum",
"of",
"the",
"max_depth",
"parameter",
"which",
"defaults",
"to",
"64",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L214-L236 | train |
saltstack/salt | salt/modules/win_file.py | gid_to_group | def gid_to_group(gid):
'''
Convert the group id to the group name on this system
Under Windows, because groups are just another ACL entity, this function
behaves the same as uid_to_user.
For maintaining Windows systems, this function is superfluous and only
exists for API compatibility with Unix. Use the uid_to_user function
instead; an info level log entry will be generated if this function is used
directly.
Args:
gid (str): The gid of the group
Returns:
str: The name of the group
CLI Example:
.. code-block:: bash
salt '*' file.gid_to_group S-1-5-21-626487655-2533044672-482107328-1010
'''
func_name = '{0}.gid_to_group'.format(__virtualname__)
if __opts__.get('fun', '') == func_name:
log.info('The function %s should not be used on Windows systems; '
'see function docs for details.', func_name)
return uid_to_user(gid) | python | def gid_to_group(gid):
'''
Convert the group id to the group name on this system
Under Windows, because groups are just another ACL entity, this function
behaves the same as uid_to_user.
For maintaining Windows systems, this function is superfluous and only
exists for API compatibility with Unix. Use the uid_to_user function
instead; an info level log entry will be generated if this function is used
directly.
Args:
gid (str): The gid of the group
Returns:
str: The name of the group
CLI Example:
.. code-block:: bash
salt '*' file.gid_to_group S-1-5-21-626487655-2533044672-482107328-1010
'''
func_name = '{0}.gid_to_group'.format(__virtualname__)
if __opts__.get('fun', '') == func_name:
log.info('The function %s should not be used on Windows systems; '
'see function docs for details.', func_name)
return uid_to_user(gid) | [
"def",
"gid_to_group",
"(",
"gid",
")",
":",
"func_name",
"=",
"'{0}.gid_to_group'",
".",
"format",
"(",
"__virtualname__",
")",
"if",
"__opts__",
".",
"get",
"(",
"'fun'",
",",
"''",
")",
"==",
"func_name",
":",
"log",
".",
"info",
"(",
"'The function %s ... | Convert the group id to the group name on this system
Under Windows, because groups are just another ACL entity, this function
behaves the same as uid_to_user.
For maintaining Windows systems, this function is superfluous and only
exists for API compatibility with Unix. Use the uid_to_user function
instead; an info level log entry will be generated if this function is used
directly.
Args:
gid (str): The gid of the group
Returns:
str: The name of the group
CLI Example:
.. code-block:: bash
salt '*' file.gid_to_group S-1-5-21-626487655-2533044672-482107328-1010 | [
"Convert",
"the",
"group",
"id",
"to",
"the",
"group",
"name",
"on",
"this",
"system"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L239-L268 | train |
saltstack/salt | salt/modules/win_file.py | group_to_gid | def group_to_gid(group):
'''
Convert the group to the gid on this system
Under Windows, because groups are just another ACL entity, this function
behaves the same as user_to_uid, except if None is given, '' is returned.
For maintaining Windows systems, this function is superfluous and only
exists for API compatibility with Unix. Use the user_to_uid function
instead; an info level log entry will be generated if this function is used
directly.
Args:
group (str): The name of the group
Returns:
str: The gid of the group
CLI Example:
.. code-block:: bash
salt '*' file.group_to_gid administrators
'''
func_name = '{0}.group_to_gid'.format(__virtualname__)
if __opts__.get('fun', '') == func_name:
log.info('The function %s should not be used on Windows systems; '
'see function docs for details.', func_name)
if group is None:
return ''
return salt.utils.win_dacl.get_sid_string(group) | python | def group_to_gid(group):
'''
Convert the group to the gid on this system
Under Windows, because groups are just another ACL entity, this function
behaves the same as user_to_uid, except if None is given, '' is returned.
For maintaining Windows systems, this function is superfluous and only
exists for API compatibility with Unix. Use the user_to_uid function
instead; an info level log entry will be generated if this function is used
directly.
Args:
group (str): The name of the group
Returns:
str: The gid of the group
CLI Example:
.. code-block:: bash
salt '*' file.group_to_gid administrators
'''
func_name = '{0}.group_to_gid'.format(__virtualname__)
if __opts__.get('fun', '') == func_name:
log.info('The function %s should not be used on Windows systems; '
'see function docs for details.', func_name)
if group is None:
return ''
return salt.utils.win_dacl.get_sid_string(group) | [
"def",
"group_to_gid",
"(",
"group",
")",
":",
"func_name",
"=",
"'{0}.group_to_gid'",
".",
"format",
"(",
"__virtualname__",
")",
"if",
"__opts__",
".",
"get",
"(",
"'fun'",
",",
"''",
")",
"==",
"func_name",
":",
"log",
".",
"info",
"(",
"'The function %... | Convert the group to the gid on this system
Under Windows, because groups are just another ACL entity, this function
behaves the same as user_to_uid, except if None is given, '' is returned.
For maintaining Windows systems, this function is superfluous and only
exists for API compatibility with Unix. Use the user_to_uid function
instead; an info level log entry will be generated if this function is used
directly.
Args:
group (str): The name of the group
Returns:
str: The gid of the group
CLI Example:
.. code-block:: bash
salt '*' file.group_to_gid administrators | [
"Convert",
"the",
"group",
"to",
"the",
"gid",
"on",
"this",
"system"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L271-L303 | train |
saltstack/salt | salt/modules/win_file.py | get_pgid | def get_pgid(path, follow_symlinks=True):
'''
Return the id of the primary group that owns a given file (Windows only)
This function will return the rarely used primary group of a file. This
generally has no bearing on permissions unless intentionally configured
and is most commonly used to provide Unix compatibility (e.g. Services
For Unix, NFS services).
Ensure you know what you are doing before using this function.
Args:
path (str): The path to the file or directory
follow_symlinks (bool):
If the object specified by ``path`` is a symlink, get attributes of
the linked file instead of the symlink itself. Default is True
Returns:
str: The gid of the primary group
CLI Example:
.. code-block:: bash
salt '*' file.get_pgid c:\\temp\\test.txt
'''
if not os.path.exists(path):
raise CommandExecutionError('Path not found: {0}'.format(path))
# Under Windows, if the path is a symlink, the user that owns the symlink is
# returned, not the user that owns the file/directory the symlink is
# pointing to. This behavior is *different* to *nix, therefore the symlink
# is first resolved manually if necessary. Remember symlinks are only
# supported on Windows Vista or later.
if follow_symlinks and sys.getwindowsversion().major >= 6:
path = _resolve_symlink(path)
group_name = salt.utils.win_dacl.get_primary_group(path)
return salt.utils.win_dacl.get_sid_string(group_name) | python | def get_pgid(path, follow_symlinks=True):
'''
Return the id of the primary group that owns a given file (Windows only)
This function will return the rarely used primary group of a file. This
generally has no bearing on permissions unless intentionally configured
and is most commonly used to provide Unix compatibility (e.g. Services
For Unix, NFS services).
Ensure you know what you are doing before using this function.
Args:
path (str): The path to the file or directory
follow_symlinks (bool):
If the object specified by ``path`` is a symlink, get attributes of
the linked file instead of the symlink itself. Default is True
Returns:
str: The gid of the primary group
CLI Example:
.. code-block:: bash
salt '*' file.get_pgid c:\\temp\\test.txt
'''
if not os.path.exists(path):
raise CommandExecutionError('Path not found: {0}'.format(path))
# Under Windows, if the path is a symlink, the user that owns the symlink is
# returned, not the user that owns the file/directory the symlink is
# pointing to. This behavior is *different* to *nix, therefore the symlink
# is first resolved manually if necessary. Remember symlinks are only
# supported on Windows Vista or later.
if follow_symlinks and sys.getwindowsversion().major >= 6:
path = _resolve_symlink(path)
group_name = salt.utils.win_dacl.get_primary_group(path)
return salt.utils.win_dacl.get_sid_string(group_name) | [
"def",
"get_pgid",
"(",
"path",
",",
"follow_symlinks",
"=",
"True",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'Path not found: {0}'",
".",
"format",
"(",
"path",
")",
")",
"# ... | Return the id of the primary group that owns a given file (Windows only)
This function will return the rarely used primary group of a file. This
generally has no bearing on permissions unless intentionally configured
and is most commonly used to provide Unix compatibility (e.g. Services
For Unix, NFS services).
Ensure you know what you are doing before using this function.
Args:
path (str): The path to the file or directory
follow_symlinks (bool):
If the object specified by ``path`` is a symlink, get attributes of
the linked file instead of the symlink itself. Default is True
Returns:
str: The gid of the primary group
CLI Example:
.. code-block:: bash
salt '*' file.get_pgid c:\\temp\\test.txt | [
"Return",
"the",
"id",
"of",
"the",
"primary",
"group",
"that",
"owns",
"a",
"given",
"file",
"(",
"Windows",
"only",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L306-L345 | train |
saltstack/salt | salt/modules/win_file.py | get_gid | def get_gid(path, follow_symlinks=True):
'''
Return the id of the group that owns a given file
Under Windows, this will return the uid of the file.
While a file in Windows does have a 'primary group', this rarely used
attribute generally has no bearing on permissions unless intentionally
configured and is only used to support Unix compatibility features (e.g.
Services For Unix, NFS services).
Salt, therefore, remaps this function to provide functionality that
somewhat resembles Unix behavior for API compatibility reasons. When
managing Windows systems, this function is superfluous and will generate
an info level log entry if used directly.
If you do actually want to access the 'primary group' of a file, use
`file.get_pgid`.
Args:
path (str): The path to the file or directory
follow_symlinks (bool):
If the object specified by ``path`` is a symlink, get attributes of
the linked file instead of the symlink itself. Default is True
Returns:
str: The gid of the owner
CLI Example:
.. code-block:: bash
salt '*' file.get_gid c:\\temp\\test.txt
'''
func_name = '{0}.get_gid'.format(__virtualname__)
if __opts__.get('fun', '') == func_name:
log.info('The function %s should not be used on Windows systems; '
'see function docs for details. The value returned is the '
'uid.', func_name)
return get_uid(path, follow_symlinks) | python | def get_gid(path, follow_symlinks=True):
'''
Return the id of the group that owns a given file
Under Windows, this will return the uid of the file.
While a file in Windows does have a 'primary group', this rarely used
attribute generally has no bearing on permissions unless intentionally
configured and is only used to support Unix compatibility features (e.g.
Services For Unix, NFS services).
Salt, therefore, remaps this function to provide functionality that
somewhat resembles Unix behavior for API compatibility reasons. When
managing Windows systems, this function is superfluous and will generate
an info level log entry if used directly.
If you do actually want to access the 'primary group' of a file, use
`file.get_pgid`.
Args:
path (str): The path to the file or directory
follow_symlinks (bool):
If the object specified by ``path`` is a symlink, get attributes of
the linked file instead of the symlink itself. Default is True
Returns:
str: The gid of the owner
CLI Example:
.. code-block:: bash
salt '*' file.get_gid c:\\temp\\test.txt
'''
func_name = '{0}.get_gid'.format(__virtualname__)
if __opts__.get('fun', '') == func_name:
log.info('The function %s should not be used on Windows systems; '
'see function docs for details. The value returned is the '
'uid.', func_name)
return get_uid(path, follow_symlinks) | [
"def",
"get_gid",
"(",
"path",
",",
"follow_symlinks",
"=",
"True",
")",
":",
"func_name",
"=",
"'{0}.get_gid'",
".",
"format",
"(",
"__virtualname__",
")",
"if",
"__opts__",
".",
"get",
"(",
"'fun'",
",",
"''",
")",
"==",
"func_name",
":",
"log",
".",
... | Return the id of the group that owns a given file
Under Windows, this will return the uid of the file.
While a file in Windows does have a 'primary group', this rarely used
attribute generally has no bearing on permissions unless intentionally
configured and is only used to support Unix compatibility features (e.g.
Services For Unix, NFS services).
Salt, therefore, remaps this function to provide functionality that
somewhat resembles Unix behavior for API compatibility reasons. When
managing Windows systems, this function is superfluous and will generate
an info level log entry if used directly.
If you do actually want to access the 'primary group' of a file, use
`file.get_pgid`.
Args:
path (str): The path to the file or directory
follow_symlinks (bool):
If the object specified by ``path`` is a symlink, get attributes of
the linked file instead of the symlink itself. Default is True
Returns:
str: The gid of the owner
CLI Example:
.. code-block:: bash
salt '*' file.get_gid c:\\temp\\test.txt | [
"Return",
"the",
"id",
"of",
"the",
"group",
"that",
"owns",
"a",
"given",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L383-L424 | train |
saltstack/salt | salt/modules/win_file.py | get_group | def get_group(path, follow_symlinks=True):
'''
Return the group that owns a given file
Under Windows, this will return the user (owner) of the file.
While a file in Windows does have a 'primary group', this rarely used
attribute generally has no bearing on permissions unless intentionally
configured and is only used to support Unix compatibility features (e.g.
Services For Unix, NFS services).
Salt, therefore, remaps this function to provide functionality that
somewhat resembles Unix behavior for API compatibility reasons. When
managing Windows systems, this function is superfluous and will generate
an info level log entry if used directly.
If you do actually want to access the 'primary group' of a file, use
`file.get_pgroup`.
Args:
path (str): The path to the file or directory
follow_symlinks (bool):
If the object specified by ``path`` is a symlink, get attributes of
the linked file instead of the symlink itself. Default is True
Returns:
str: The name of the owner
CLI Example:
.. code-block:: bash
salt '*' file.get_group c:\\temp\\test.txt
'''
func_name = '{0}.get_group'.format(__virtualname__)
if __opts__.get('fun', '') == func_name:
log.info('The function %s should not be used on Windows systems; '
'see function docs for details. The value returned is the '
'user (owner).', func_name)
return get_user(path, follow_symlinks) | python | def get_group(path, follow_symlinks=True):
'''
Return the group that owns a given file
Under Windows, this will return the user (owner) of the file.
While a file in Windows does have a 'primary group', this rarely used
attribute generally has no bearing on permissions unless intentionally
configured and is only used to support Unix compatibility features (e.g.
Services For Unix, NFS services).
Salt, therefore, remaps this function to provide functionality that
somewhat resembles Unix behavior for API compatibility reasons. When
managing Windows systems, this function is superfluous and will generate
an info level log entry if used directly.
If you do actually want to access the 'primary group' of a file, use
`file.get_pgroup`.
Args:
path (str): The path to the file or directory
follow_symlinks (bool):
If the object specified by ``path`` is a symlink, get attributes of
the linked file instead of the symlink itself. Default is True
Returns:
str: The name of the owner
CLI Example:
.. code-block:: bash
salt '*' file.get_group c:\\temp\\test.txt
'''
func_name = '{0}.get_group'.format(__virtualname__)
if __opts__.get('fun', '') == func_name:
log.info('The function %s should not be used on Windows systems; '
'see function docs for details. The value returned is the '
'user (owner).', func_name)
return get_user(path, follow_symlinks) | [
"def",
"get_group",
"(",
"path",
",",
"follow_symlinks",
"=",
"True",
")",
":",
"func_name",
"=",
"'{0}.get_group'",
".",
"format",
"(",
"__virtualname__",
")",
"if",
"__opts__",
".",
"get",
"(",
"'fun'",
",",
"''",
")",
"==",
"func_name",
":",
"log",
".... | Return the group that owns a given file
Under Windows, this will return the user (owner) of the file.
While a file in Windows does have a 'primary group', this rarely used
attribute generally has no bearing on permissions unless intentionally
configured and is only used to support Unix compatibility features (e.g.
Services For Unix, NFS services).
Salt, therefore, remaps this function to provide functionality that
somewhat resembles Unix behavior for API compatibility reasons. When
managing Windows systems, this function is superfluous and will generate
an info level log entry if used directly.
If you do actually want to access the 'primary group' of a file, use
`file.get_pgroup`.
Args:
path (str): The path to the file or directory
follow_symlinks (bool):
If the object specified by ``path`` is a symlink, get attributes of
the linked file instead of the symlink itself. Default is True
Returns:
str: The name of the owner
CLI Example:
.. code-block:: bash
salt '*' file.get_group c:\\temp\\test.txt | [
"Return",
"the",
"group",
"that",
"owns",
"a",
"given",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L427-L468 | train |
saltstack/salt | salt/modules/win_file.py | user_to_uid | def user_to_uid(user):
'''
Convert user name to a uid
Args:
user (str): The user to lookup
Returns:
str: The user id of the user
CLI Example:
.. code-block:: bash
salt '*' file.user_to_uid myusername
'''
if user is None:
user = salt.utils.user.get_user()
return salt.utils.win_dacl.get_sid_string(user) | python | def user_to_uid(user):
'''
Convert user name to a uid
Args:
user (str): The user to lookup
Returns:
str: The user id of the user
CLI Example:
.. code-block:: bash
salt '*' file.user_to_uid myusername
'''
if user is None:
user = salt.utils.user.get_user()
return salt.utils.win_dacl.get_sid_string(user) | [
"def",
"user_to_uid",
"(",
"user",
")",
":",
"if",
"user",
"is",
"None",
":",
"user",
"=",
"salt",
".",
"utils",
".",
"user",
".",
"get_user",
"(",
")",
"return",
"salt",
".",
"utils",
".",
"win_dacl",
".",
"get_sid_string",
"(",
"user",
")"
] | Convert user name to a uid
Args:
user (str): The user to lookup
Returns:
str: The user id of the user
CLI Example:
.. code-block:: bash
salt '*' file.user_to_uid myusername | [
"Convert",
"user",
"name",
"to",
"a",
"uid"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L493-L512 | train |
saltstack/salt | salt/modules/win_file.py | get_uid | def get_uid(path, follow_symlinks=True):
'''
Return the id of the user that owns a given file
Symlinks are followed by default to mimic Unix behavior. Specify
`follow_symlinks=False` to turn off this behavior.
Args:
path (str): The path to the file or directory
follow_symlinks (bool):
If the object specified by ``path`` is a symlink, get attributes of
the linked file instead of the symlink itself. Default is True
Returns:
str: The uid of the owner
CLI Example:
.. code-block:: bash
salt '*' file.get_uid c:\\temp\\test.txt
salt '*' file.get_uid c:\\temp\\test.txt follow_symlinks=False
'''
if not os.path.exists(path):
raise CommandExecutionError('Path not found: {0}'.format(path))
# Under Windows, if the path is a symlink, the user that owns the symlink is
# returned, not the user that owns the file/directory the symlink is
# pointing to. This behavior is *different* to *nix, therefore the symlink
# is first resolved manually if necessary. Remember symlinks are only
# supported on Windows Vista or later.
if follow_symlinks and sys.getwindowsversion().major >= 6:
path = _resolve_symlink(path)
owner_sid = salt.utils.win_dacl.get_owner(path)
return salt.utils.win_dacl.get_sid_string(owner_sid) | python | def get_uid(path, follow_symlinks=True):
'''
Return the id of the user that owns a given file
Symlinks are followed by default to mimic Unix behavior. Specify
`follow_symlinks=False` to turn off this behavior.
Args:
path (str): The path to the file or directory
follow_symlinks (bool):
If the object specified by ``path`` is a symlink, get attributes of
the linked file instead of the symlink itself. Default is True
Returns:
str: The uid of the owner
CLI Example:
.. code-block:: bash
salt '*' file.get_uid c:\\temp\\test.txt
salt '*' file.get_uid c:\\temp\\test.txt follow_symlinks=False
'''
if not os.path.exists(path):
raise CommandExecutionError('Path not found: {0}'.format(path))
# Under Windows, if the path is a symlink, the user that owns the symlink is
# returned, not the user that owns the file/directory the symlink is
# pointing to. This behavior is *different* to *nix, therefore the symlink
# is first resolved manually if necessary. Remember symlinks are only
# supported on Windows Vista or later.
if follow_symlinks and sys.getwindowsversion().major >= 6:
path = _resolve_symlink(path)
owner_sid = salt.utils.win_dacl.get_owner(path)
return salt.utils.win_dacl.get_sid_string(owner_sid) | [
"def",
"get_uid",
"(",
"path",
",",
"follow_symlinks",
"=",
"True",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'Path not found: {0}'",
".",
"format",
"(",
"path",
")",
")",
"# U... | Return the id of the user that owns a given file
Symlinks are followed by default to mimic Unix behavior. Specify
`follow_symlinks=False` to turn off this behavior.
Args:
path (str): The path to the file or directory
follow_symlinks (bool):
If the object specified by ``path`` is a symlink, get attributes of
the linked file instead of the symlink itself. Default is True
Returns:
str: The uid of the owner
CLI Example:
.. code-block:: bash
salt '*' file.get_uid c:\\temp\\test.txt
salt '*' file.get_uid c:\\temp\\test.txt follow_symlinks=False | [
"Return",
"the",
"id",
"of",
"the",
"user",
"that",
"owns",
"a",
"given",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L515-L552 | train |
saltstack/salt | salt/modules/win_file.py | get_user | def get_user(path, follow_symlinks=True):
'''
Return the user that owns a given file
Symlinks are followed by default to mimic Unix behavior. Specify
`follow_symlinks=False` to turn off this behavior.
Args:
path (str): The path to the file or directory
follow_symlinks (bool):
If the object specified by ``path`` is a symlink, get attributes of
the linked file instead of the symlink itself. Default is True
Returns:
str: The name of the owner
CLI Example:
.. code-block:: bash
salt '*' file.get_user c:\\temp\\test.txt
salt '*' file.get_user c:\\temp\\test.txt follow_symlinks=False
'''
if not os.path.exists(path):
raise CommandExecutionError('Path not found: {0}'.format(path))
# Under Windows, if the path is a symlink, the user that owns the symlink is
# returned, not the user that owns the file/directory the symlink is
# pointing to. This behavior is *different* to *nix, therefore the symlink
# is first resolved manually if necessary. Remember symlinks are only
# supported on Windows Vista or later.
if follow_symlinks and sys.getwindowsversion().major >= 6:
path = _resolve_symlink(path)
return salt.utils.win_dacl.get_owner(path) | python | def get_user(path, follow_symlinks=True):
'''
Return the user that owns a given file
Symlinks are followed by default to mimic Unix behavior. Specify
`follow_symlinks=False` to turn off this behavior.
Args:
path (str): The path to the file or directory
follow_symlinks (bool):
If the object specified by ``path`` is a symlink, get attributes of
the linked file instead of the symlink itself. Default is True
Returns:
str: The name of the owner
CLI Example:
.. code-block:: bash
salt '*' file.get_user c:\\temp\\test.txt
salt '*' file.get_user c:\\temp\\test.txt follow_symlinks=False
'''
if not os.path.exists(path):
raise CommandExecutionError('Path not found: {0}'.format(path))
# Under Windows, if the path is a symlink, the user that owns the symlink is
# returned, not the user that owns the file/directory the symlink is
# pointing to. This behavior is *different* to *nix, therefore the symlink
# is first resolved manually if necessary. Remember symlinks are only
# supported on Windows Vista or later.
if follow_symlinks and sys.getwindowsversion().major >= 6:
path = _resolve_symlink(path)
return salt.utils.win_dacl.get_owner(path) | [
"def",
"get_user",
"(",
"path",
",",
"follow_symlinks",
"=",
"True",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'Path not found: {0}'",
".",
"format",
"(",
"path",
")",
")",
"# ... | Return the user that owns a given file
Symlinks are followed by default to mimic Unix behavior. Specify
`follow_symlinks=False` to turn off this behavior.
Args:
path (str): The path to the file or directory
follow_symlinks (bool):
If the object specified by ``path`` is a symlink, get attributes of
the linked file instead of the symlink itself. Default is True
Returns:
str: The name of the owner
CLI Example:
.. code-block:: bash
salt '*' file.get_user c:\\temp\\test.txt
salt '*' file.get_user c:\\temp\\test.txt follow_symlinks=False | [
"Return",
"the",
"user",
"that",
"owns",
"a",
"given",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L555-L591 | train |
saltstack/salt | salt/modules/win_file.py | get_mode | def get_mode(path):
'''
Return the mode of a file
Right now we're just returning None because Windows' doesn't have a mode
like Linux
Args:
path (str): The path to the file or directory
Returns:
None
CLI Example:
.. code-block:: bash
salt '*' file.get_mode /etc/passwd
'''
if not os.path.exists(path):
raise CommandExecutionError('Path not found: {0}'.format(path))
func_name = '{0}.get_mode'.format(__virtualname__)
if __opts__.get('fun', '') == func_name:
log.info('The function %s should not be used on Windows systems; '
'see function docs for details. The value returned is '
'always None.', func_name)
return None | python | def get_mode(path):
'''
Return the mode of a file
Right now we're just returning None because Windows' doesn't have a mode
like Linux
Args:
path (str): The path to the file or directory
Returns:
None
CLI Example:
.. code-block:: bash
salt '*' file.get_mode /etc/passwd
'''
if not os.path.exists(path):
raise CommandExecutionError('Path not found: {0}'.format(path))
func_name = '{0}.get_mode'.format(__virtualname__)
if __opts__.get('fun', '') == func_name:
log.info('The function %s should not be used on Windows systems; '
'see function docs for details. The value returned is '
'always None.', func_name)
return None | [
"def",
"get_mode",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'Path not found: {0}'",
".",
"format",
"(",
"path",
")",
")",
"func_name",
"=",
"'{0}.get_mode'",
".",
... | Return the mode of a file
Right now we're just returning None because Windows' doesn't have a mode
like Linux
Args:
path (str): The path to the file or directory
Returns:
None
CLI Example:
.. code-block:: bash
salt '*' file.get_mode /etc/passwd | [
"Return",
"the",
"mode",
"of",
"a",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L594-L622 | train |
saltstack/salt | salt/modules/win_file.py | lchown | def lchown(path, user, group=None, pgroup=None):
'''
Chown a file, pass the file the desired user and group without following any
symlinks.
Under Windows, the group parameter will be ignored.
This is because while files in Windows do have a 'primary group'
property, this is rarely used. It generally has no bearing on
permissions unless intentionally configured and is most commonly used to
provide Unix compatibility (e.g. Services For Unix, NFS services).
If you do want to change the 'primary group' property and understand the
implications, pass the Windows only parameter, pgroup, instead.
To set the primary group to 'None', it must be specified in quotes.
Otherwise Salt will interpret it as the Python value of None and no primary
group changes will occur. See the example below.
Args:
path (str): The path to the file or directory
user (str): The name of the user to own the file
group (str): The group (not used)
pgroup (str): The primary group to assign
Returns:
bool: True if successful, otherwise error
CLI Example:
.. code-block:: bash
salt '*' file.lchown c:\\temp\\test.txt myusername
salt '*' file.lchown c:\\temp\\test.txt myusername pgroup=Administrators
salt '*' file.lchown c:\\temp\\test.txt myusername "pgroup='None'"
'''
if group:
func_name = '{0}.lchown'.format(__virtualname__)
if __opts__.get('fun', '') == func_name:
log.info('The group parameter has no effect when using %s on '
'Windows systems; see function docs for details.',
func_name)
log.debug('win_file.py %s Ignoring the group parameter for %s',
func_name, path)
group = None
return chown(path, user, group, pgroup, follow_symlinks=False) | python | def lchown(path, user, group=None, pgroup=None):
'''
Chown a file, pass the file the desired user and group without following any
symlinks.
Under Windows, the group parameter will be ignored.
This is because while files in Windows do have a 'primary group'
property, this is rarely used. It generally has no bearing on
permissions unless intentionally configured and is most commonly used to
provide Unix compatibility (e.g. Services For Unix, NFS services).
If you do want to change the 'primary group' property and understand the
implications, pass the Windows only parameter, pgroup, instead.
To set the primary group to 'None', it must be specified in quotes.
Otherwise Salt will interpret it as the Python value of None and no primary
group changes will occur. See the example below.
Args:
path (str): The path to the file or directory
user (str): The name of the user to own the file
group (str): The group (not used)
pgroup (str): The primary group to assign
Returns:
bool: True if successful, otherwise error
CLI Example:
.. code-block:: bash
salt '*' file.lchown c:\\temp\\test.txt myusername
salt '*' file.lchown c:\\temp\\test.txt myusername pgroup=Administrators
salt '*' file.lchown c:\\temp\\test.txt myusername "pgroup='None'"
'''
if group:
func_name = '{0}.lchown'.format(__virtualname__)
if __opts__.get('fun', '') == func_name:
log.info('The group parameter has no effect when using %s on '
'Windows systems; see function docs for details.',
func_name)
log.debug('win_file.py %s Ignoring the group parameter for %s',
func_name, path)
group = None
return chown(path, user, group, pgroup, follow_symlinks=False) | [
"def",
"lchown",
"(",
"path",
",",
"user",
",",
"group",
"=",
"None",
",",
"pgroup",
"=",
"None",
")",
":",
"if",
"group",
":",
"func_name",
"=",
"'{0}.lchown'",
".",
"format",
"(",
"__virtualname__",
")",
"if",
"__opts__",
".",
"get",
"(",
"'fun'",
... | Chown a file, pass the file the desired user and group without following any
symlinks.
Under Windows, the group parameter will be ignored.
This is because while files in Windows do have a 'primary group'
property, this is rarely used. It generally has no bearing on
permissions unless intentionally configured and is most commonly used to
provide Unix compatibility (e.g. Services For Unix, NFS services).
If you do want to change the 'primary group' property and understand the
implications, pass the Windows only parameter, pgroup, instead.
To set the primary group to 'None', it must be specified in quotes.
Otherwise Salt will interpret it as the Python value of None and no primary
group changes will occur. See the example below.
Args:
path (str): The path to the file or directory
user (str): The name of the user to own the file
group (str): The group (not used)
pgroup (str): The primary group to assign
Returns:
bool: True if successful, otherwise error
CLI Example:
.. code-block:: bash
salt '*' file.lchown c:\\temp\\test.txt myusername
salt '*' file.lchown c:\\temp\\test.txt myusername pgroup=Administrators
salt '*' file.lchown c:\\temp\\test.txt myusername "pgroup='None'" | [
"Chown",
"a",
"file",
"pass",
"the",
"file",
"the",
"desired",
"user",
"and",
"group",
"without",
"following",
"any",
"symlinks",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L625-L671 | train |
saltstack/salt | salt/modules/win_file.py | chown | def chown(path, user, group=None, pgroup=None, follow_symlinks=True):
'''
Chown a file, pass the file the desired user and group
Under Windows, the group parameter will be ignored.
This is because while files in Windows do have a 'primary group'
property, this is rarely used. It generally has no bearing on
permissions unless intentionally configured and is most commonly used to
provide Unix compatibility (e.g. Services For Unix, NFS services).
If you do want to change the 'primary group' property and understand the
implications, pass the Windows only parameter, pgroup, instead.
Args:
path (str): The path to the file or directory
user (str): The name of the user to own the file
group (str): The group (not used)
pgroup (str): The primary group to assign
follow_symlinks (bool):
If the object specified by ``path`` is a symlink, get attributes of
the linked file instead of the symlink itself. Default is True
Returns:
bool: True if successful, otherwise error
CLI Example:
.. code-block:: bash
salt '*' file.chown c:\\temp\\test.txt myusername
salt '*' file.chown c:\\temp\\test.txt myusername pgroup=Administrators
salt '*' file.chown c:\\temp\\test.txt myusername "pgroup='None'"
'''
# the group parameter is not used; only provided for API compatibility
if group is not None:
func_name = '{0}.chown'.format(__virtualname__)
if __opts__.get('fun', '') == func_name:
log.info('The group parameter has no effect when using %s on '
'Windows systems; see function docs for details.',
func_name)
log.debug('win_file.py %s Ignoring the group parameter for %s',
func_name, path)
if follow_symlinks and sys.getwindowsversion().major >= 6:
path = _resolve_symlink(path)
if not os.path.exists(path):
raise CommandExecutionError('Path not found: {0}'.format(path))
salt.utils.win_dacl.set_owner(path, user)
if pgroup:
salt.utils.win_dacl.set_primary_group(path, pgroup)
return True | python | def chown(path, user, group=None, pgroup=None, follow_symlinks=True):
'''
Chown a file, pass the file the desired user and group
Under Windows, the group parameter will be ignored.
This is because while files in Windows do have a 'primary group'
property, this is rarely used. It generally has no bearing on
permissions unless intentionally configured and is most commonly used to
provide Unix compatibility (e.g. Services For Unix, NFS services).
If you do want to change the 'primary group' property and understand the
implications, pass the Windows only parameter, pgroup, instead.
Args:
path (str): The path to the file or directory
user (str): The name of the user to own the file
group (str): The group (not used)
pgroup (str): The primary group to assign
follow_symlinks (bool):
If the object specified by ``path`` is a symlink, get attributes of
the linked file instead of the symlink itself. Default is True
Returns:
bool: True if successful, otherwise error
CLI Example:
.. code-block:: bash
salt '*' file.chown c:\\temp\\test.txt myusername
salt '*' file.chown c:\\temp\\test.txt myusername pgroup=Administrators
salt '*' file.chown c:\\temp\\test.txt myusername "pgroup='None'"
'''
# the group parameter is not used; only provided for API compatibility
if group is not None:
func_name = '{0}.chown'.format(__virtualname__)
if __opts__.get('fun', '') == func_name:
log.info('The group parameter has no effect when using %s on '
'Windows systems; see function docs for details.',
func_name)
log.debug('win_file.py %s Ignoring the group parameter for %s',
func_name, path)
if follow_symlinks and sys.getwindowsversion().major >= 6:
path = _resolve_symlink(path)
if not os.path.exists(path):
raise CommandExecutionError('Path not found: {0}'.format(path))
salt.utils.win_dacl.set_owner(path, user)
if pgroup:
salt.utils.win_dacl.set_primary_group(path, pgroup)
return True | [
"def",
"chown",
"(",
"path",
",",
"user",
",",
"group",
"=",
"None",
",",
"pgroup",
"=",
"None",
",",
"follow_symlinks",
"=",
"True",
")",
":",
"# the group parameter is not used; only provided for API compatibility",
"if",
"group",
"is",
"not",
"None",
":",
"fu... | Chown a file, pass the file the desired user and group
Under Windows, the group parameter will be ignored.
This is because while files in Windows do have a 'primary group'
property, this is rarely used. It generally has no bearing on
permissions unless intentionally configured and is most commonly used to
provide Unix compatibility (e.g. Services For Unix, NFS services).
If you do want to change the 'primary group' property and understand the
implications, pass the Windows only parameter, pgroup, instead.
Args:
path (str): The path to the file or directory
user (str): The name of the user to own the file
group (str): The group (not used)
pgroup (str): The primary group to assign
follow_symlinks (bool):
If the object specified by ``path`` is a symlink, get attributes of
the linked file instead of the symlink itself. Default is True
Returns:
bool: True if successful, otherwise error
CLI Example:
.. code-block:: bash
salt '*' file.chown c:\\temp\\test.txt myusername
salt '*' file.chown c:\\temp\\test.txt myusername pgroup=Administrators
salt '*' file.chown c:\\temp\\test.txt myusername "pgroup='None'" | [
"Chown",
"a",
"file",
"pass",
"the",
"file",
"the",
"desired",
"user",
"and",
"group"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L674-L728 | train |
saltstack/salt | salt/modules/win_file.py | chgrp | def chgrp(path, group):
'''
Change the group of a file
Under Windows, this will do nothing.
While a file in Windows does have a 'primary group', this rarely used
attribute generally has no bearing on permissions unless intentionally
configured and is only used to support Unix compatibility features (e.g.
Services For Unix, NFS services).
Salt, therefore, remaps this function to do nothing while still being
compatible with Unix behavior. When managing Windows systems,
this function is superfluous and will generate an info level log entry if
used directly.
If you do actually want to set the 'primary group' of a file, use ``file
.chpgrp``.
To set group permissions use ``file.set_perms``
Args:
path (str): The path to the file or directory
group (str): The group (unused)
Returns:
None
CLI Example:
.. code-block:: bash
salt '*' file.chpgrp c:\\temp\\test.txt administrators
'''
func_name = '{0}.chgrp'.format(__virtualname__)
if __opts__.get('fun', '') == func_name:
log.info('The function %s should not be used on Windows systems; see '
'function docs for details.', func_name)
log.debug('win_file.py %s Doing nothing for %s', func_name, path)
return None | python | def chgrp(path, group):
'''
Change the group of a file
Under Windows, this will do nothing.
While a file in Windows does have a 'primary group', this rarely used
attribute generally has no bearing on permissions unless intentionally
configured and is only used to support Unix compatibility features (e.g.
Services For Unix, NFS services).
Salt, therefore, remaps this function to do nothing while still being
compatible with Unix behavior. When managing Windows systems,
this function is superfluous and will generate an info level log entry if
used directly.
If you do actually want to set the 'primary group' of a file, use ``file
.chpgrp``.
To set group permissions use ``file.set_perms``
Args:
path (str): The path to the file or directory
group (str): The group (unused)
Returns:
None
CLI Example:
.. code-block:: bash
salt '*' file.chpgrp c:\\temp\\test.txt administrators
'''
func_name = '{0}.chgrp'.format(__virtualname__)
if __opts__.get('fun', '') == func_name:
log.info('The function %s should not be used on Windows systems; see '
'function docs for details.', func_name)
log.debug('win_file.py %s Doing nothing for %s', func_name, path)
return None | [
"def",
"chgrp",
"(",
"path",
",",
"group",
")",
":",
"func_name",
"=",
"'{0}.chgrp'",
".",
"format",
"(",
"__virtualname__",
")",
"if",
"__opts__",
".",
"get",
"(",
"'fun'",
",",
"''",
")",
"==",
"func_name",
":",
"log",
".",
"info",
"(",
"'The functio... | Change the group of a file
Under Windows, this will do nothing.
While a file in Windows does have a 'primary group', this rarely used
attribute generally has no bearing on permissions unless intentionally
configured and is only used to support Unix compatibility features (e.g.
Services For Unix, NFS services).
Salt, therefore, remaps this function to do nothing while still being
compatible with Unix behavior. When managing Windows systems,
this function is superfluous and will generate an info level log entry if
used directly.
If you do actually want to set the 'primary group' of a file, use ``file
.chpgrp``.
To set group permissions use ``file.set_perms``
Args:
path (str): The path to the file or directory
group (str): The group (unused)
Returns:
None
CLI Example:
.. code-block:: bash
salt '*' file.chpgrp c:\\temp\\test.txt administrators | [
"Change",
"the",
"group",
"of",
"a",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L759-L799 | train |
saltstack/salt | salt/modules/win_file.py | stats | def stats(path, hash_type='sha256', follow_symlinks=True):
'''
Return a dict containing the stats about a given file
Under Windows, `gid` will equal `uid` and `group` will equal `user`.
While a file in Windows does have a 'primary group', this rarely used
attribute generally has no bearing on permissions unless intentionally
configured and is only used to support Unix compatibility features (e.g.
Services For Unix, NFS services).
Salt, therefore, remaps these properties to keep some kind of
compatibility with Unix behavior. If the 'primary group' is required, it
can be accessed in the `pgroup` and `pgid` properties.
Args:
path (str): The path to the file or directory
hash_type (str): The type of hash to return
follow_symlinks (bool):
If the object specified by ``path`` is a symlink, get attributes of
the linked file instead of the symlink itself. Default is True
Returns:
dict: A dictionary of file/directory stats
CLI Example:
.. code-block:: bash
salt '*' file.stats /etc/passwd
'''
# This is to mirror the behavior of file.py. `check_file_meta` expects an
# empty dictionary when the file does not exist
if not os.path.exists(path):
raise CommandExecutionError('Path not found: {0}'.format(path))
if follow_symlinks and sys.getwindowsversion().major >= 6:
path = _resolve_symlink(path)
pstat = os.stat(path)
ret = {}
ret['inode'] = pstat.st_ino
# don't need to resolve symlinks again because we've already done that
ret['uid'] = get_uid(path, follow_symlinks=False)
# maintain the illusion that group is the same as user as states need this
ret['gid'] = ret['uid']
ret['user'] = uid_to_user(ret['uid'])
ret['group'] = ret['user']
ret['pgid'] = get_pgid(path, follow_symlinks)
ret['pgroup'] = gid_to_group(ret['pgid'])
ret['atime'] = pstat.st_atime
ret['mtime'] = pstat.st_mtime
ret['ctime'] = pstat.st_ctime
ret['size'] = pstat.st_size
ret['mode'] = six.text_type(oct(stat.S_IMODE(pstat.st_mode)))
if hash_type:
ret['sum'] = get_sum(path, hash_type)
ret['type'] = 'file'
if stat.S_ISDIR(pstat.st_mode):
ret['type'] = 'dir'
if stat.S_ISCHR(pstat.st_mode):
ret['type'] = 'char'
if stat.S_ISBLK(pstat.st_mode):
ret['type'] = 'block'
if stat.S_ISREG(pstat.st_mode):
ret['type'] = 'file'
if stat.S_ISLNK(pstat.st_mode):
ret['type'] = 'link'
if stat.S_ISFIFO(pstat.st_mode):
ret['type'] = 'pipe'
if stat.S_ISSOCK(pstat.st_mode):
ret['type'] = 'socket'
ret['target'] = os.path.realpath(path)
return ret | python | def stats(path, hash_type='sha256', follow_symlinks=True):
'''
Return a dict containing the stats about a given file
Under Windows, `gid` will equal `uid` and `group` will equal `user`.
While a file in Windows does have a 'primary group', this rarely used
attribute generally has no bearing on permissions unless intentionally
configured and is only used to support Unix compatibility features (e.g.
Services For Unix, NFS services).
Salt, therefore, remaps these properties to keep some kind of
compatibility with Unix behavior. If the 'primary group' is required, it
can be accessed in the `pgroup` and `pgid` properties.
Args:
path (str): The path to the file or directory
hash_type (str): The type of hash to return
follow_symlinks (bool):
If the object specified by ``path`` is a symlink, get attributes of
the linked file instead of the symlink itself. Default is True
Returns:
dict: A dictionary of file/directory stats
CLI Example:
.. code-block:: bash
salt '*' file.stats /etc/passwd
'''
# This is to mirror the behavior of file.py. `check_file_meta` expects an
# empty dictionary when the file does not exist
if not os.path.exists(path):
raise CommandExecutionError('Path not found: {0}'.format(path))
if follow_symlinks and sys.getwindowsversion().major >= 6:
path = _resolve_symlink(path)
pstat = os.stat(path)
ret = {}
ret['inode'] = pstat.st_ino
# don't need to resolve symlinks again because we've already done that
ret['uid'] = get_uid(path, follow_symlinks=False)
# maintain the illusion that group is the same as user as states need this
ret['gid'] = ret['uid']
ret['user'] = uid_to_user(ret['uid'])
ret['group'] = ret['user']
ret['pgid'] = get_pgid(path, follow_symlinks)
ret['pgroup'] = gid_to_group(ret['pgid'])
ret['atime'] = pstat.st_atime
ret['mtime'] = pstat.st_mtime
ret['ctime'] = pstat.st_ctime
ret['size'] = pstat.st_size
ret['mode'] = six.text_type(oct(stat.S_IMODE(pstat.st_mode)))
if hash_type:
ret['sum'] = get_sum(path, hash_type)
ret['type'] = 'file'
if stat.S_ISDIR(pstat.st_mode):
ret['type'] = 'dir'
if stat.S_ISCHR(pstat.st_mode):
ret['type'] = 'char'
if stat.S_ISBLK(pstat.st_mode):
ret['type'] = 'block'
if stat.S_ISREG(pstat.st_mode):
ret['type'] = 'file'
if stat.S_ISLNK(pstat.st_mode):
ret['type'] = 'link'
if stat.S_ISFIFO(pstat.st_mode):
ret['type'] = 'pipe'
if stat.S_ISSOCK(pstat.st_mode):
ret['type'] = 'socket'
ret['target'] = os.path.realpath(path)
return ret | [
"def",
"stats",
"(",
"path",
",",
"hash_type",
"=",
"'sha256'",
",",
"follow_symlinks",
"=",
"True",
")",
":",
"# This is to mirror the behavior of file.py. `check_file_meta` expects an",
"# empty dictionary when the file does not exist",
"if",
"not",
"os",
".",
"path",
"."... | Return a dict containing the stats about a given file
Under Windows, `gid` will equal `uid` and `group` will equal `user`.
While a file in Windows does have a 'primary group', this rarely used
attribute generally has no bearing on permissions unless intentionally
configured and is only used to support Unix compatibility features (e.g.
Services For Unix, NFS services).
Salt, therefore, remaps these properties to keep some kind of
compatibility with Unix behavior. If the 'primary group' is required, it
can be accessed in the `pgroup` and `pgid` properties.
Args:
path (str): The path to the file or directory
hash_type (str): The type of hash to return
follow_symlinks (bool):
If the object specified by ``path`` is a symlink, get attributes of
the linked file instead of the symlink itself. Default is True
Returns:
dict: A dictionary of file/directory stats
CLI Example:
.. code-block:: bash
salt '*' file.stats /etc/passwd | [
"Return",
"a",
"dict",
"containing",
"the",
"stats",
"about",
"a",
"given",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L802-L876 | train |
saltstack/salt | salt/modules/win_file.py | get_attributes | def get_attributes(path):
'''
Return a dictionary object with the Windows
file attributes for a file.
Args:
path (str): The path to the file or directory
Returns:
dict: A dictionary of file attributes
CLI Example:
.. code-block:: bash
salt '*' file.get_attributes c:\\temp\\a.txt
'''
if not os.path.exists(path):
raise CommandExecutionError('Path not found: {0}'.format(path))
# set up dictionary for attribute values
attributes = {}
# Get cumulative int value of attributes
intAttributes = win32file.GetFileAttributes(path)
# Assign individual attributes
attributes['archive'] = (intAttributes & 32) == 32
attributes['reparsePoint'] = (intAttributes & 1024) == 1024
attributes['compressed'] = (intAttributes & 2048) == 2048
attributes['directory'] = (intAttributes & 16) == 16
attributes['encrypted'] = (intAttributes & 16384) == 16384
attributes['hidden'] = (intAttributes & 2) == 2
attributes['normal'] = (intAttributes & 128) == 128
attributes['notIndexed'] = (intAttributes & 8192) == 8192
attributes['offline'] = (intAttributes & 4096) == 4096
attributes['readonly'] = (intAttributes & 1) == 1
attributes['system'] = (intAttributes & 4) == 4
attributes['temporary'] = (intAttributes & 256) == 256
# check if it's a Mounted Volume
attributes['mountedVolume'] = False
if attributes['reparsePoint'] is True and attributes['directory'] is True:
fileIterator = win32file.FindFilesIterator(path)
findDataTuple = next(fileIterator)
if findDataTuple[6] == 0xA0000003:
attributes['mountedVolume'] = True
# check if it's a soft (symbolic) link
# Note: os.path.islink() does not work in
# Python 2.7 for the Windows NTFS file system.
# The following code does, however, work (tested in Windows 8)
attributes['symbolicLink'] = False
if attributes['reparsePoint'] is True:
fileIterator = win32file.FindFilesIterator(path)
findDataTuple = next(fileIterator)
if findDataTuple[6] == 0xA000000C:
attributes['symbolicLink'] = True
return attributes | python | def get_attributes(path):
'''
Return a dictionary object with the Windows
file attributes for a file.
Args:
path (str): The path to the file or directory
Returns:
dict: A dictionary of file attributes
CLI Example:
.. code-block:: bash
salt '*' file.get_attributes c:\\temp\\a.txt
'''
if not os.path.exists(path):
raise CommandExecutionError('Path not found: {0}'.format(path))
# set up dictionary for attribute values
attributes = {}
# Get cumulative int value of attributes
intAttributes = win32file.GetFileAttributes(path)
# Assign individual attributes
attributes['archive'] = (intAttributes & 32) == 32
attributes['reparsePoint'] = (intAttributes & 1024) == 1024
attributes['compressed'] = (intAttributes & 2048) == 2048
attributes['directory'] = (intAttributes & 16) == 16
attributes['encrypted'] = (intAttributes & 16384) == 16384
attributes['hidden'] = (intAttributes & 2) == 2
attributes['normal'] = (intAttributes & 128) == 128
attributes['notIndexed'] = (intAttributes & 8192) == 8192
attributes['offline'] = (intAttributes & 4096) == 4096
attributes['readonly'] = (intAttributes & 1) == 1
attributes['system'] = (intAttributes & 4) == 4
attributes['temporary'] = (intAttributes & 256) == 256
# check if it's a Mounted Volume
attributes['mountedVolume'] = False
if attributes['reparsePoint'] is True and attributes['directory'] is True:
fileIterator = win32file.FindFilesIterator(path)
findDataTuple = next(fileIterator)
if findDataTuple[6] == 0xA0000003:
attributes['mountedVolume'] = True
# check if it's a soft (symbolic) link
# Note: os.path.islink() does not work in
# Python 2.7 for the Windows NTFS file system.
# The following code does, however, work (tested in Windows 8)
attributes['symbolicLink'] = False
if attributes['reparsePoint'] is True:
fileIterator = win32file.FindFilesIterator(path)
findDataTuple = next(fileIterator)
if findDataTuple[6] == 0xA000000C:
attributes['symbolicLink'] = True
return attributes | [
"def",
"get_attributes",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"CommandExecutionError",
"(",
"'Path not found: {0}'",
".",
"format",
"(",
"path",
")",
")",
"# set up dictionary for attribute values"... | Return a dictionary object with the Windows
file attributes for a file.
Args:
path (str): The path to the file or directory
Returns:
dict: A dictionary of file attributes
CLI Example:
.. code-block:: bash
salt '*' file.get_attributes c:\\temp\\a.txt | [
"Return",
"a",
"dictionary",
"object",
"with",
"the",
"Windows",
"file",
"attributes",
"for",
"a",
"file",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L879-L939 | train |
saltstack/salt | salt/modules/win_file.py | set_attributes | def set_attributes(path, archive=None, hidden=None, normal=None,
notIndexed=None, readonly=None, system=None, temporary=None):
'''
Set file attributes for a file. Note that the normal attribute
means that all others are false. So setting it will clear all others.
Args:
path (str): The path to the file or directory
archive (bool): Sets the archive attribute. Default is None
hidden (bool): Sets the hidden attribute. Default is None
normal (bool):
Resets the file attributes. Cannot be used in conjunction with any
other attribute. Default is None
notIndexed (bool): Sets the indexed attribute. Default is None
readonly (bool): Sets the readonly attribute. Default is None
system (bool): Sets the system attribute. Default is None
temporary (bool): Sets the temporary attribute. Default is None
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' file.set_attributes c:\\temp\\a.txt normal=True
salt '*' file.set_attributes c:\\temp\\a.txt readonly=True hidden=True
'''
if not os.path.exists(path):
raise CommandExecutionError('Path not found: {0}'.format(path))
if normal:
if archive or hidden or notIndexed or readonly or system or temporary:
raise CommandExecutionError(
'Normal attribute may not be used with any other attributes')
ret = win32file.SetFileAttributes(path, 128)
return True if ret is None else False
# Get current attributes
intAttributes = win32file.GetFileAttributes(path)
# individually set or clear bits for appropriate attributes
if archive is not None:
if archive:
intAttributes |= 0x20
else:
intAttributes &= 0xFFDF
if hidden is not None:
if hidden:
intAttributes |= 0x2
else:
intAttributes &= 0xFFFD
if notIndexed is not None:
if notIndexed:
intAttributes |= 0x2000
else:
intAttributes &= 0xDFFF
if readonly is not None:
if readonly:
intAttributes |= 0x1
else:
intAttributes &= 0xFFFE
if system is not None:
if system:
intAttributes |= 0x4
else:
intAttributes &= 0xFFFB
if temporary is not None:
if temporary:
intAttributes |= 0x100
else:
intAttributes &= 0xFEFF
ret = win32file.SetFileAttributes(path, intAttributes)
return True if ret is None else False | python | def set_attributes(path, archive=None, hidden=None, normal=None,
notIndexed=None, readonly=None, system=None, temporary=None):
'''
Set file attributes for a file. Note that the normal attribute
means that all others are false. So setting it will clear all others.
Args:
path (str): The path to the file or directory
archive (bool): Sets the archive attribute. Default is None
hidden (bool): Sets the hidden attribute. Default is None
normal (bool):
Resets the file attributes. Cannot be used in conjunction with any
other attribute. Default is None
notIndexed (bool): Sets the indexed attribute. Default is None
readonly (bool): Sets the readonly attribute. Default is None
system (bool): Sets the system attribute. Default is None
temporary (bool): Sets the temporary attribute. Default is None
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' file.set_attributes c:\\temp\\a.txt normal=True
salt '*' file.set_attributes c:\\temp\\a.txt readonly=True hidden=True
'''
if not os.path.exists(path):
raise CommandExecutionError('Path not found: {0}'.format(path))
if normal:
if archive or hidden or notIndexed or readonly or system or temporary:
raise CommandExecutionError(
'Normal attribute may not be used with any other attributes')
ret = win32file.SetFileAttributes(path, 128)
return True if ret is None else False
# Get current attributes
intAttributes = win32file.GetFileAttributes(path)
# individually set or clear bits for appropriate attributes
if archive is not None:
if archive:
intAttributes |= 0x20
else:
intAttributes &= 0xFFDF
if hidden is not None:
if hidden:
intAttributes |= 0x2
else:
intAttributes &= 0xFFFD
if notIndexed is not None:
if notIndexed:
intAttributes |= 0x2000
else:
intAttributes &= 0xDFFF
if readonly is not None:
if readonly:
intAttributes |= 0x1
else:
intAttributes &= 0xFFFE
if system is not None:
if system:
intAttributes |= 0x4
else:
intAttributes &= 0xFFFB
if temporary is not None:
if temporary:
intAttributes |= 0x100
else:
intAttributes &= 0xFEFF
ret = win32file.SetFileAttributes(path, intAttributes)
return True if ret is None else False | [
"def",
"set_attributes",
"(",
"path",
",",
"archive",
"=",
"None",
",",
"hidden",
"=",
"None",
",",
"normal",
"=",
"None",
",",
"notIndexed",
"=",
"None",
",",
"readonly",
"=",
"None",
",",
"system",
"=",
"None",
",",
"temporary",
"=",
"None",
")",
"... | Set file attributes for a file. Note that the normal attribute
means that all others are false. So setting it will clear all others.
Args:
path (str): The path to the file or directory
archive (bool): Sets the archive attribute. Default is None
hidden (bool): Sets the hidden attribute. Default is None
normal (bool):
Resets the file attributes. Cannot be used in conjunction with any
other attribute. Default is None
notIndexed (bool): Sets the indexed attribute. Default is None
readonly (bool): Sets the readonly attribute. Default is None
system (bool): Sets the system attribute. Default is None
temporary (bool): Sets the temporary attribute. Default is None
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' file.set_attributes c:\\temp\\a.txt normal=True
salt '*' file.set_attributes c:\\temp\\a.txt readonly=True hidden=True | [
"Set",
"file",
"attributes",
"for",
"a",
"file",
".",
"Note",
"that",
"the",
"normal",
"attribute",
"means",
"that",
"all",
"others",
"are",
"false",
".",
"So",
"setting",
"it",
"will",
"clear",
"all",
"others",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L942-L1016 | train |
saltstack/salt | salt/modules/win_file.py | set_mode | def set_mode(path, mode):
'''
Set the mode of a file
This just calls get_mode, which returns None because we don't use mode on
Windows
Args:
path: The path to the file or directory
mode: The mode (not used)
Returns:
None
CLI Example:
.. code-block:: bash
salt '*' file.set_mode /etc/passwd 0644
'''
func_name = '{0}.set_mode'.format(__virtualname__)
if __opts__.get('fun', '') == func_name:
log.info('The function %s should not be used on Windows systems; '
'see function docs for details. The value returned is '
'always None. Use set_perms instead.', func_name)
return get_mode(path) | python | def set_mode(path, mode):
'''
Set the mode of a file
This just calls get_mode, which returns None because we don't use mode on
Windows
Args:
path: The path to the file or directory
mode: The mode (not used)
Returns:
None
CLI Example:
.. code-block:: bash
salt '*' file.set_mode /etc/passwd 0644
'''
func_name = '{0}.set_mode'.format(__virtualname__)
if __opts__.get('fun', '') == func_name:
log.info('The function %s should not be used on Windows systems; '
'see function docs for details. The value returned is '
'always None. Use set_perms instead.', func_name)
return get_mode(path) | [
"def",
"set_mode",
"(",
"path",
",",
"mode",
")",
":",
"func_name",
"=",
"'{0}.set_mode'",
".",
"format",
"(",
"__virtualname__",
")",
"if",
"__opts__",
".",
"get",
"(",
"'fun'",
",",
"''",
")",
"==",
"func_name",
":",
"log",
".",
"info",
"(",
"'The fu... | Set the mode of a file
This just calls get_mode, which returns None because we don't use mode on
Windows
Args:
path: The path to the file or directory
mode: The mode (not used)
Returns:
None
CLI Example:
.. code-block:: bash
salt '*' file.set_mode /etc/passwd 0644 | [
"Set",
"the",
"mode",
"of",
"a",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L1019-L1045 | train |
saltstack/salt | salt/modules/win_file.py | remove | def remove(path, force=False):
'''
Remove the named file or directory
Args:
path (str): The path to the file or directory to remove.
force (bool): Remove even if marked Read-Only. Default is False
Returns:
bool: True if successful, False if unsuccessful
CLI Example:
.. code-block:: bash
salt '*' file.remove C:\\Temp
'''
# This must be a recursive function in windows to properly deal with
# Symlinks. The shutil.rmtree function will remove the contents of
# the Symlink source in windows.
path = os.path.expanduser(path)
if not os.path.isabs(path):
raise SaltInvocationError('File path must be absolute: {0}'.format(path))
# Does the file/folder exists
if not os.path.exists(path) and not is_link(path):
raise CommandExecutionError('Path not found: {0}'.format(path))
# Remove ReadOnly Attribute
if force:
# Get current file attributes
file_attributes = win32api.GetFileAttributes(path)
win32api.SetFileAttributes(path, win32con.FILE_ATTRIBUTE_NORMAL)
try:
if os.path.isfile(path):
# A file and a symlinked file are removed the same way
os.remove(path)
elif is_link(path):
# If it's a symlink directory, use the rmdir command
os.rmdir(path)
else:
for name in os.listdir(path):
item = '{0}\\{1}'.format(path, name)
# If it's a normal directory, recurse to remove it's contents
remove(item, force)
# rmdir will work now because the directory is empty
os.rmdir(path)
except (OSError, IOError) as exc:
if force:
# Reset attributes to the original if delete fails.
win32api.SetFileAttributes(path, file_attributes)
raise CommandExecutionError(
'Could not remove \'{0}\': {1}'.format(path, exc)
)
return True | python | def remove(path, force=False):
'''
Remove the named file or directory
Args:
path (str): The path to the file or directory to remove.
force (bool): Remove even if marked Read-Only. Default is False
Returns:
bool: True if successful, False if unsuccessful
CLI Example:
.. code-block:: bash
salt '*' file.remove C:\\Temp
'''
# This must be a recursive function in windows to properly deal with
# Symlinks. The shutil.rmtree function will remove the contents of
# the Symlink source in windows.
path = os.path.expanduser(path)
if not os.path.isabs(path):
raise SaltInvocationError('File path must be absolute: {0}'.format(path))
# Does the file/folder exists
if not os.path.exists(path) and not is_link(path):
raise CommandExecutionError('Path not found: {0}'.format(path))
# Remove ReadOnly Attribute
if force:
# Get current file attributes
file_attributes = win32api.GetFileAttributes(path)
win32api.SetFileAttributes(path, win32con.FILE_ATTRIBUTE_NORMAL)
try:
if os.path.isfile(path):
# A file and a symlinked file are removed the same way
os.remove(path)
elif is_link(path):
# If it's a symlink directory, use the rmdir command
os.rmdir(path)
else:
for name in os.listdir(path):
item = '{0}\\{1}'.format(path, name)
# If it's a normal directory, recurse to remove it's contents
remove(item, force)
# rmdir will work now because the directory is empty
os.rmdir(path)
except (OSError, IOError) as exc:
if force:
# Reset attributes to the original if delete fails.
win32api.SetFileAttributes(path, file_attributes)
raise CommandExecutionError(
'Could not remove \'{0}\': {1}'.format(path, exc)
)
return True | [
"def",
"remove",
"(",
"path",
",",
"force",
"=",
"False",
")",
":",
"# This must be a recursive function in windows to properly deal with",
"# Symlinks. The shutil.rmtree function will remove the contents of",
"# the Symlink source in windows.",
"path",
"=",
"os",
".",
"path",
".... | Remove the named file or directory
Args:
path (str): The path to the file or directory to remove.
force (bool): Remove even if marked Read-Only. Default is False
Returns:
bool: True if successful, False if unsuccessful
CLI Example:
.. code-block:: bash
salt '*' file.remove C:\\Temp | [
"Remove",
"the",
"named",
"file",
"or",
"directory"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L1048-L1107 | train |
saltstack/salt | salt/modules/win_file.py | symlink | def symlink(src, link):
'''
Create a symbolic link to a file
This is only supported with Windows Vista or later and must be executed by
a user with the SeCreateSymbolicLink privilege.
The behavior of this function matches the Unix equivalent, with one
exception - invalid symlinks cannot be created. The source path must exist.
If it doesn't, an error will be raised.
Args:
src (str): The path to a file or directory
link (str): The path to the link
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' file.symlink /path/to/file /path/to/link
'''
# When Python 3.2 or later becomes the minimum version, this function can be
# replaced with the built-in os.symlink function, which supports Windows.
if sys.getwindowsversion().major < 6:
raise SaltInvocationError('Symlinks are only supported on Windows Vista or later.')
if not os.path.exists(src):
raise SaltInvocationError('The given source path does not exist.')
if not os.path.isabs(src):
raise SaltInvocationError('File path must be absolute.')
# ensure paths are using the right slashes
src = os.path.normpath(src)
link = os.path.normpath(link)
is_dir = os.path.isdir(src)
try:
win32file.CreateSymbolicLink(link, src, int(is_dir))
return True
except pywinerror as exc:
raise CommandExecutionError(
'Could not create \'{0}\' - [{1}] {2}'.format(
link,
exc.winerror,
exc.strerror
)
) | python | def symlink(src, link):
'''
Create a symbolic link to a file
This is only supported with Windows Vista or later and must be executed by
a user with the SeCreateSymbolicLink privilege.
The behavior of this function matches the Unix equivalent, with one
exception - invalid symlinks cannot be created. The source path must exist.
If it doesn't, an error will be raised.
Args:
src (str): The path to a file or directory
link (str): The path to the link
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' file.symlink /path/to/file /path/to/link
'''
# When Python 3.2 or later becomes the minimum version, this function can be
# replaced with the built-in os.symlink function, which supports Windows.
if sys.getwindowsversion().major < 6:
raise SaltInvocationError('Symlinks are only supported on Windows Vista or later.')
if not os.path.exists(src):
raise SaltInvocationError('The given source path does not exist.')
if not os.path.isabs(src):
raise SaltInvocationError('File path must be absolute.')
# ensure paths are using the right slashes
src = os.path.normpath(src)
link = os.path.normpath(link)
is_dir = os.path.isdir(src)
try:
win32file.CreateSymbolicLink(link, src, int(is_dir))
return True
except pywinerror as exc:
raise CommandExecutionError(
'Could not create \'{0}\' - [{1}] {2}'.format(
link,
exc.winerror,
exc.strerror
)
) | [
"def",
"symlink",
"(",
"src",
",",
"link",
")",
":",
"# When Python 3.2 or later becomes the minimum version, this function can be",
"# replaced with the built-in os.symlink function, which supports Windows.",
"if",
"sys",
".",
"getwindowsversion",
"(",
")",
".",
"major",
"<",
... | Create a symbolic link to a file
This is only supported with Windows Vista or later and must be executed by
a user with the SeCreateSymbolicLink privilege.
The behavior of this function matches the Unix equivalent, with one
exception - invalid symlinks cannot be created. The source path must exist.
If it doesn't, an error will be raised.
Args:
src (str): The path to a file or directory
link (str): The path to the link
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' file.symlink /path/to/file /path/to/link | [
"Create",
"a",
"symbolic",
"link",
"to",
"a",
"file"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L1110-L1161 | train |
saltstack/salt | salt/modules/win_file.py | is_link | def is_link(path):
'''
Check if the path is a symlink
This is only supported on Windows Vista or later.
Inline with Unix behavior, this function will raise an error if the path
is not a symlink, however, the error raised will be a SaltInvocationError,
not an OSError.
Args:
path (str): The path to a file or directory
Returns:
bool: True if path is a symlink, otherwise False
CLI Example:
.. code-block:: bash
salt '*' file.is_link /path/to/link
'''
if sys.getwindowsversion().major < 6:
raise SaltInvocationError('Symlinks are only supported on Windows Vista or later.')
try:
return salt.utils.path.islink(path)
except Exception as exc:
raise CommandExecutionError(exc) | python | def is_link(path):
'''
Check if the path is a symlink
This is only supported on Windows Vista or later.
Inline with Unix behavior, this function will raise an error if the path
is not a symlink, however, the error raised will be a SaltInvocationError,
not an OSError.
Args:
path (str): The path to a file or directory
Returns:
bool: True if path is a symlink, otherwise False
CLI Example:
.. code-block:: bash
salt '*' file.is_link /path/to/link
'''
if sys.getwindowsversion().major < 6:
raise SaltInvocationError('Symlinks are only supported on Windows Vista or later.')
try:
return salt.utils.path.islink(path)
except Exception as exc:
raise CommandExecutionError(exc) | [
"def",
"is_link",
"(",
"path",
")",
":",
"if",
"sys",
".",
"getwindowsversion",
"(",
")",
".",
"major",
"<",
"6",
":",
"raise",
"SaltInvocationError",
"(",
"'Symlinks are only supported on Windows Vista or later.'",
")",
"try",
":",
"return",
"salt",
".",
"utils... | Check if the path is a symlink
This is only supported on Windows Vista or later.
Inline with Unix behavior, this function will raise an error if the path
is not a symlink, however, the error raised will be a SaltInvocationError,
not an OSError.
Args:
path (str): The path to a file or directory
Returns:
bool: True if path is a symlink, otherwise False
CLI Example:
.. code-block:: bash
salt '*' file.is_link /path/to/link | [
"Check",
"if",
"the",
"path",
"is",
"a",
"symlink"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L1164-L1192 | train |
saltstack/salt | salt/modules/win_file.py | readlink | def readlink(path):
'''
Return the path that a symlink points to
This is only supported on Windows Vista or later.
Inline with Unix behavior, this function will raise an error if the path is
not a symlink, however, the error raised will be a SaltInvocationError, not
an OSError.
Args:
path (str): The path to the symlink
Returns:
str: The path that the symlink points to
CLI Example:
.. code-block:: bash
salt '*' file.readlink /path/to/link
'''
if sys.getwindowsversion().major < 6:
raise SaltInvocationError('Symlinks are only supported on Windows Vista or later.')
try:
return salt.utils.path.readlink(path)
except OSError as exc:
if exc.errno == errno.EINVAL:
raise CommandExecutionError('{0} is not a symbolic link'.format(path))
raise CommandExecutionError(exc.__str__())
except Exception as exc:
raise CommandExecutionError(exc) | python | def readlink(path):
'''
Return the path that a symlink points to
This is only supported on Windows Vista or later.
Inline with Unix behavior, this function will raise an error if the path is
not a symlink, however, the error raised will be a SaltInvocationError, not
an OSError.
Args:
path (str): The path to the symlink
Returns:
str: The path that the symlink points to
CLI Example:
.. code-block:: bash
salt '*' file.readlink /path/to/link
'''
if sys.getwindowsversion().major < 6:
raise SaltInvocationError('Symlinks are only supported on Windows Vista or later.')
try:
return salt.utils.path.readlink(path)
except OSError as exc:
if exc.errno == errno.EINVAL:
raise CommandExecutionError('{0} is not a symbolic link'.format(path))
raise CommandExecutionError(exc.__str__())
except Exception as exc:
raise CommandExecutionError(exc) | [
"def",
"readlink",
"(",
"path",
")",
":",
"if",
"sys",
".",
"getwindowsversion",
"(",
")",
".",
"major",
"<",
"6",
":",
"raise",
"SaltInvocationError",
"(",
"'Symlinks are only supported on Windows Vista or later.'",
")",
"try",
":",
"return",
"salt",
".",
"util... | Return the path that a symlink points to
This is only supported on Windows Vista or later.
Inline with Unix behavior, this function will raise an error if the path is
not a symlink, however, the error raised will be a SaltInvocationError, not
an OSError.
Args:
path (str): The path to the symlink
Returns:
str: The path that the symlink points to
CLI Example:
.. code-block:: bash
salt '*' file.readlink /path/to/link | [
"Return",
"the",
"path",
"that",
"a",
"symlink",
"points",
"to"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L1195-L1227 | train |
saltstack/salt | salt/modules/win_file.py | mkdir | def mkdir(path,
owner=None,
grant_perms=None,
deny_perms=None,
inheritance=True,
reset=False):
'''
Ensure that the directory is available and permissions are set.
Args:
path (str):
The full path to the directory.
owner (str):
The owner of the directory. If not passed, it will be the account
that created the directory, likely SYSTEM
grant_perms (dict):
A dictionary containing the user/group and the basic permissions to
grant, ie: ``{'user': {'perms': 'basic_permission'}}``. You can also
set the ``applies_to`` setting here. The default is
``this_folder_subfolders_files``. Specify another ``applies_to``
setting like this:
.. code-block:: yaml
{'user': {'perms': 'full_control', 'applies_to': 'this_folder'}}
To set advanced permissions use a list for the ``perms`` parameter,
ie:
.. code-block:: yaml
{'user': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder'}}
deny_perms (dict):
A dictionary containing the user/group and permissions to deny along
with the ``applies_to`` setting. Use the same format used for the
``grant_perms`` parameter. Remember, deny permissions supersede
grant permissions.
inheritance (bool):
If True the object will inherit permissions from the parent, if
``False``, inheritance will be disabled. Inheritance setting will
not apply to parent directories if they must be created.
reset (bool):
If ``True`` the existing DACL will be cleared and replaced with the
settings defined in this function. If ``False``, new entries will be
appended to the existing DACL. Default is ``False``.
.. versionadded:: 2018.3.0
Returns:
bool: True if successful
Raises:
CommandExecutionError: If unsuccessful
CLI Example:
.. code-block:: bash
# To grant the 'Users' group 'read & execute' permissions.
salt '*' file.mkdir C:\\Temp\\ Administrators "{'Users': {'perms': 'read_execute'}}"
# Locally using salt call
salt-call file.mkdir C:\\Temp\\ Administrators "{'Users': {'perms': 'read_execute', 'applies_to': 'this_folder_only'}}"
# Specify advanced attributes with a list
salt '*' file.mkdir C:\\Temp\\ Administrators "{'jsnuffy': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder_only'}}"
'''
# Make sure the drive is valid
drive = os.path.splitdrive(path)[0]
if not os.path.isdir(drive):
raise CommandExecutionError('Drive {0} is not mapped'.format(drive))
path = os.path.expanduser(path)
path = os.path.expandvars(path)
if not os.path.isdir(path):
try:
# Make the directory
os.mkdir(path)
# Set owner
if owner:
salt.utils.win_dacl.set_owner(obj_name=path, principal=owner)
# Set permissions
set_perms(
path=path,
grant_perms=grant_perms,
deny_perms=deny_perms,
inheritance=inheritance,
reset=reset)
except WindowsError as exc:
raise CommandExecutionError(exc)
return True | python | def mkdir(path,
owner=None,
grant_perms=None,
deny_perms=None,
inheritance=True,
reset=False):
'''
Ensure that the directory is available and permissions are set.
Args:
path (str):
The full path to the directory.
owner (str):
The owner of the directory. If not passed, it will be the account
that created the directory, likely SYSTEM
grant_perms (dict):
A dictionary containing the user/group and the basic permissions to
grant, ie: ``{'user': {'perms': 'basic_permission'}}``. You can also
set the ``applies_to`` setting here. The default is
``this_folder_subfolders_files``. Specify another ``applies_to``
setting like this:
.. code-block:: yaml
{'user': {'perms': 'full_control', 'applies_to': 'this_folder'}}
To set advanced permissions use a list for the ``perms`` parameter,
ie:
.. code-block:: yaml
{'user': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder'}}
deny_perms (dict):
A dictionary containing the user/group and permissions to deny along
with the ``applies_to`` setting. Use the same format used for the
``grant_perms`` parameter. Remember, deny permissions supersede
grant permissions.
inheritance (bool):
If True the object will inherit permissions from the parent, if
``False``, inheritance will be disabled. Inheritance setting will
not apply to parent directories if they must be created.
reset (bool):
If ``True`` the existing DACL will be cleared and replaced with the
settings defined in this function. If ``False``, new entries will be
appended to the existing DACL. Default is ``False``.
.. versionadded:: 2018.3.0
Returns:
bool: True if successful
Raises:
CommandExecutionError: If unsuccessful
CLI Example:
.. code-block:: bash
# To grant the 'Users' group 'read & execute' permissions.
salt '*' file.mkdir C:\\Temp\\ Administrators "{'Users': {'perms': 'read_execute'}}"
# Locally using salt call
salt-call file.mkdir C:\\Temp\\ Administrators "{'Users': {'perms': 'read_execute', 'applies_to': 'this_folder_only'}}"
# Specify advanced attributes with a list
salt '*' file.mkdir C:\\Temp\\ Administrators "{'jsnuffy': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder_only'}}"
'''
# Make sure the drive is valid
drive = os.path.splitdrive(path)[0]
if not os.path.isdir(drive):
raise CommandExecutionError('Drive {0} is not mapped'.format(drive))
path = os.path.expanduser(path)
path = os.path.expandvars(path)
if not os.path.isdir(path):
try:
# Make the directory
os.mkdir(path)
# Set owner
if owner:
salt.utils.win_dacl.set_owner(obj_name=path, principal=owner)
# Set permissions
set_perms(
path=path,
grant_perms=grant_perms,
deny_perms=deny_perms,
inheritance=inheritance,
reset=reset)
except WindowsError as exc:
raise CommandExecutionError(exc)
return True | [
"def",
"mkdir",
"(",
"path",
",",
"owner",
"=",
"None",
",",
"grant_perms",
"=",
"None",
",",
"deny_perms",
"=",
"None",
",",
"inheritance",
"=",
"True",
",",
"reset",
"=",
"False",
")",
":",
"# Make sure the drive is valid",
"drive",
"=",
"os",
".",
"pa... | Ensure that the directory is available and permissions are set.
Args:
path (str):
The full path to the directory.
owner (str):
The owner of the directory. If not passed, it will be the account
that created the directory, likely SYSTEM
grant_perms (dict):
A dictionary containing the user/group and the basic permissions to
grant, ie: ``{'user': {'perms': 'basic_permission'}}``. You can also
set the ``applies_to`` setting here. The default is
``this_folder_subfolders_files``. Specify another ``applies_to``
setting like this:
.. code-block:: yaml
{'user': {'perms': 'full_control', 'applies_to': 'this_folder'}}
To set advanced permissions use a list for the ``perms`` parameter,
ie:
.. code-block:: yaml
{'user': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder'}}
deny_perms (dict):
A dictionary containing the user/group and permissions to deny along
with the ``applies_to`` setting. Use the same format used for the
``grant_perms`` parameter. Remember, deny permissions supersede
grant permissions.
inheritance (bool):
If True the object will inherit permissions from the parent, if
``False``, inheritance will be disabled. Inheritance setting will
not apply to parent directories if they must be created.
reset (bool):
If ``True`` the existing DACL will be cleared and replaced with the
settings defined in this function. If ``False``, new entries will be
appended to the existing DACL. Default is ``False``.
.. versionadded:: 2018.3.0
Returns:
bool: True if successful
Raises:
CommandExecutionError: If unsuccessful
CLI Example:
.. code-block:: bash
# To grant the 'Users' group 'read & execute' permissions.
salt '*' file.mkdir C:\\Temp\\ Administrators "{'Users': {'perms': 'read_execute'}}"
# Locally using salt call
salt-call file.mkdir C:\\Temp\\ Administrators "{'Users': {'perms': 'read_execute', 'applies_to': 'this_folder_only'}}"
# Specify advanced attributes with a list
salt '*' file.mkdir C:\\Temp\\ Administrators "{'jsnuffy': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder_only'}}" | [
"Ensure",
"that",
"the",
"directory",
"is",
"available",
"and",
"permissions",
"are",
"set",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L1230-L1332 | train |
saltstack/salt | salt/modules/win_file.py | makedirs_ | def makedirs_(path,
owner=None,
grant_perms=None,
deny_perms=None,
inheritance=True,
reset=False):
'''
Ensure that the parent directory containing this path is available.
Args:
path (str):
The full path to the directory.
.. note::
The path must end with a trailing slash otherwise the
directory(s) will be created up to the parent directory. For
example if path is ``C:\\temp\\test``, then it would be treated
as ``C:\\temp\\`` but if the path ends with a trailing slash
like ``C:\\temp\\test\\``, then it would be treated as
``C:\\temp\\test\\``.
owner (str):
The owner of the directory. If not passed, it will be the account
that created the directory, likely SYSTEM.
grant_perms (dict):
A dictionary containing the user/group and the basic permissions to
grant, ie: ``{'user': {'perms': 'basic_permission'}}``. You can also
set the ``applies_to`` setting here. The default is
``this_folder_subfolders_files``. Specify another ``applies_to``
setting like this:
.. code-block:: yaml
{'user': {'perms': 'full_control', 'applies_to': 'this_folder'}}
To set advanced permissions use a list for the ``perms`` parameter, ie:
.. code-block:: yaml
{'user': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder'}}
deny_perms (dict):
A dictionary containing the user/group and permissions to deny along
with the ``applies_to`` setting. Use the same format used for the
``grant_perms`` parameter. Remember, deny permissions supersede
grant permissions.
inheritance (bool):
If True the object will inherit permissions from the parent, if
False, inheritance will be disabled. Inheritance setting will not
apply to parent directories if they must be created.
reset (bool):
If ``True`` the existing DACL will be cleared and replaced with the
settings defined in this function. If ``False``, new entries will be
appended to the existing DACL. Default is ``False``.
.. versionadded:: 2018.3.0
Returns:
bool: True if successful
Raises:
CommandExecutionError: If unsuccessful
CLI Example:
.. code-block:: bash
# To grant the 'Users' group 'read & execute' permissions.
salt '*' file.makedirs C:\\Temp\\ Administrators "{'Users': {'perms': 'read_execute'}}"
# Locally using salt call
salt-call file.makedirs C:\\Temp\\ Administrators "{'Users': {'perms': 'read_execute', 'applies_to': 'this_folder_only'}}"
# Specify advanced attributes with a list
salt '*' file.makedirs C:\\Temp\\ Administrators "{'jsnuffy': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder_only'}}"
'''
path = os.path.expanduser(path)
# walk up the directory structure until we find the first existing
# directory
dirname = os.path.normpath(os.path.dirname(path))
if os.path.isdir(dirname):
# There's nothing for us to do
msg = 'Directory \'{0}\' already exists'.format(dirname)
log.debug(msg)
return msg
if os.path.exists(dirname):
msg = 'The path \'{0}\' already exists and is not a directory'.format(
dirname
)
log.debug(msg)
return msg
directories_to_create = []
while True:
if os.path.isdir(dirname):
break
directories_to_create.append(dirname)
current_dirname = dirname
dirname = os.path.dirname(dirname)
if current_dirname == dirname:
raise SaltInvocationError(
'Recursive creation for path \'{0}\' would result in an '
'infinite loop. Please use an absolute path.'.format(dirname)
)
# create parent directories from the topmost to the most deeply nested one
directories_to_create.reverse()
for directory_to_create in directories_to_create:
# all directories have the user, group and mode set!!
log.debug('Creating directory: %s', directory_to_create)
mkdir(
path=directory_to_create,
owner=owner,
grant_perms=grant_perms,
deny_perms=deny_perms,
inheritance=inheritance,
reset=reset)
return True | python | def makedirs_(path,
owner=None,
grant_perms=None,
deny_perms=None,
inheritance=True,
reset=False):
'''
Ensure that the parent directory containing this path is available.
Args:
path (str):
The full path to the directory.
.. note::
The path must end with a trailing slash otherwise the
directory(s) will be created up to the parent directory. For
example if path is ``C:\\temp\\test``, then it would be treated
as ``C:\\temp\\`` but if the path ends with a trailing slash
like ``C:\\temp\\test\\``, then it would be treated as
``C:\\temp\\test\\``.
owner (str):
The owner of the directory. If not passed, it will be the account
that created the directory, likely SYSTEM.
grant_perms (dict):
A dictionary containing the user/group and the basic permissions to
grant, ie: ``{'user': {'perms': 'basic_permission'}}``. You can also
set the ``applies_to`` setting here. The default is
``this_folder_subfolders_files``. Specify another ``applies_to``
setting like this:
.. code-block:: yaml
{'user': {'perms': 'full_control', 'applies_to': 'this_folder'}}
To set advanced permissions use a list for the ``perms`` parameter, ie:
.. code-block:: yaml
{'user': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder'}}
deny_perms (dict):
A dictionary containing the user/group and permissions to deny along
with the ``applies_to`` setting. Use the same format used for the
``grant_perms`` parameter. Remember, deny permissions supersede
grant permissions.
inheritance (bool):
If True the object will inherit permissions from the parent, if
False, inheritance will be disabled. Inheritance setting will not
apply to parent directories if they must be created.
reset (bool):
If ``True`` the existing DACL will be cleared and replaced with the
settings defined in this function. If ``False``, new entries will be
appended to the existing DACL. Default is ``False``.
.. versionadded:: 2018.3.0
Returns:
bool: True if successful
Raises:
CommandExecutionError: If unsuccessful
CLI Example:
.. code-block:: bash
# To grant the 'Users' group 'read & execute' permissions.
salt '*' file.makedirs C:\\Temp\\ Administrators "{'Users': {'perms': 'read_execute'}}"
# Locally using salt call
salt-call file.makedirs C:\\Temp\\ Administrators "{'Users': {'perms': 'read_execute', 'applies_to': 'this_folder_only'}}"
# Specify advanced attributes with a list
salt '*' file.makedirs C:\\Temp\\ Administrators "{'jsnuffy': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder_only'}}"
'''
path = os.path.expanduser(path)
# walk up the directory structure until we find the first existing
# directory
dirname = os.path.normpath(os.path.dirname(path))
if os.path.isdir(dirname):
# There's nothing for us to do
msg = 'Directory \'{0}\' already exists'.format(dirname)
log.debug(msg)
return msg
if os.path.exists(dirname):
msg = 'The path \'{0}\' already exists and is not a directory'.format(
dirname
)
log.debug(msg)
return msg
directories_to_create = []
while True:
if os.path.isdir(dirname):
break
directories_to_create.append(dirname)
current_dirname = dirname
dirname = os.path.dirname(dirname)
if current_dirname == dirname:
raise SaltInvocationError(
'Recursive creation for path \'{0}\' would result in an '
'infinite loop. Please use an absolute path.'.format(dirname)
)
# create parent directories from the topmost to the most deeply nested one
directories_to_create.reverse()
for directory_to_create in directories_to_create:
# all directories have the user, group and mode set!!
log.debug('Creating directory: %s', directory_to_create)
mkdir(
path=directory_to_create,
owner=owner,
grant_perms=grant_perms,
deny_perms=deny_perms,
inheritance=inheritance,
reset=reset)
return True | [
"def",
"makedirs_",
"(",
"path",
",",
"owner",
"=",
"None",
",",
"grant_perms",
"=",
"None",
",",
"deny_perms",
"=",
"None",
",",
"inheritance",
"=",
"True",
",",
"reset",
"=",
"False",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"expanduser",
"("... | Ensure that the parent directory containing this path is available.
Args:
path (str):
The full path to the directory.
.. note::
The path must end with a trailing slash otherwise the
directory(s) will be created up to the parent directory. For
example if path is ``C:\\temp\\test``, then it would be treated
as ``C:\\temp\\`` but if the path ends with a trailing slash
like ``C:\\temp\\test\\``, then it would be treated as
``C:\\temp\\test\\``.
owner (str):
The owner of the directory. If not passed, it will be the account
that created the directory, likely SYSTEM.
grant_perms (dict):
A dictionary containing the user/group and the basic permissions to
grant, ie: ``{'user': {'perms': 'basic_permission'}}``. You can also
set the ``applies_to`` setting here. The default is
``this_folder_subfolders_files``. Specify another ``applies_to``
setting like this:
.. code-block:: yaml
{'user': {'perms': 'full_control', 'applies_to': 'this_folder'}}
To set advanced permissions use a list for the ``perms`` parameter, ie:
.. code-block:: yaml
{'user': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder'}}
deny_perms (dict):
A dictionary containing the user/group and permissions to deny along
with the ``applies_to`` setting. Use the same format used for the
``grant_perms`` parameter. Remember, deny permissions supersede
grant permissions.
inheritance (bool):
If True the object will inherit permissions from the parent, if
False, inheritance will be disabled. Inheritance setting will not
apply to parent directories if they must be created.
reset (bool):
If ``True`` the existing DACL will be cleared and replaced with the
settings defined in this function. If ``False``, new entries will be
appended to the existing DACL. Default is ``False``.
.. versionadded:: 2018.3.0
Returns:
bool: True if successful
Raises:
CommandExecutionError: If unsuccessful
CLI Example:
.. code-block:: bash
# To grant the 'Users' group 'read & execute' permissions.
salt '*' file.makedirs C:\\Temp\\ Administrators "{'Users': {'perms': 'read_execute'}}"
# Locally using salt call
salt-call file.makedirs C:\\Temp\\ Administrators "{'Users': {'perms': 'read_execute', 'applies_to': 'this_folder_only'}}"
# Specify advanced attributes with a list
salt '*' file.makedirs C:\\Temp\\ Administrators "{'jsnuffy': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder_only'}}" | [
"Ensure",
"that",
"the",
"parent",
"directory",
"containing",
"this",
"path",
"is",
"available",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L1335-L1463 | train |
saltstack/salt | salt/modules/win_file.py | makedirs_perms | def makedirs_perms(path,
owner=None,
grant_perms=None,
deny_perms=None,
inheritance=True,
reset=True):
'''
Set owner and permissions for each directory created.
Args:
path (str):
The full path to the directory.
owner (str):
The owner of the directory. If not passed, it will be the account
that created the directory, likely SYSTEM.
grant_perms (dict):
A dictionary containing the user/group and the basic permissions to
grant, ie: ``{'user': {'perms': 'basic_permission'}}``. You can also
set the ``applies_to`` setting here. The default is
``this_folder_subfolders_files``. Specify another ``applies_to``
setting like this:
.. code-block:: yaml
{'user': {'perms': 'full_control', 'applies_to': 'this_folder'}}
To set advanced permissions use a list for the ``perms`` parameter, ie:
.. code-block:: yaml
{'user': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder'}}
deny_perms (dict):
A dictionary containing the user/group and permissions to deny along
with the ``applies_to`` setting. Use the same format used for the
``grant_perms`` parameter. Remember, deny permissions supersede
grant permissions.
inheritance (bool):
If ``True`` the object will inherit permissions from the parent, if
``False``, inheritance will be disabled. Inheritance setting will
not apply to parent directories if they must be created
reset (bool):
If ``True`` the existing DACL will be cleared and replaced with the
settings defined in this function. If ``False``, new entries will be
appended to the existing DACL. Default is ``False``.
.. versionadded:: 2018.3.0
Returns:
bool: True if successful, otherwise raises an error
CLI Example:
.. code-block:: bash
# To grant the 'Users' group 'read & execute' permissions.
salt '*' file.makedirs_perms C:\\Temp\\ Administrators "{'Users': {'perms': 'read_execute'}}"
# Locally using salt call
salt-call file.makedirs_perms C:\\Temp\\ Administrators "{'Users': {'perms': 'read_execute', 'applies_to': 'this_folder_only'}}"
# Specify advanced attributes with a list
salt '*' file.makedirs_perms C:\\Temp\\ Administrators "{'jsnuffy': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder_files'}}"
'''
# Expand any environment variables
path = os.path.expanduser(path)
path = os.path.expandvars(path)
# Get parent directory (head)
head, tail = os.path.split(path)
# If tail is empty, split head
if not tail:
head, tail = os.path.split(head)
# If head and tail are defined and head is not there, recurse
if head and tail and not os.path.exists(head):
try:
# Create the directory here, set inherited True because this is a
# parent directory, the inheritance setting will only apply to the
# target directory. Reset will be False as we only want to reset
# the permissions on the target directory
makedirs_perms(
path=head,
owner=owner,
grant_perms=grant_perms,
deny_perms=deny_perms,
inheritance=True,
reset=False)
except OSError as exc:
# be happy if someone already created the path
if exc.errno != errno.EEXIST:
raise
if tail == os.curdir: # xxx/newdir/. exists if xxx/newdir exists
return {}
# Make the directory
mkdir(
path=path,
owner=owner,
grant_perms=grant_perms,
deny_perms=deny_perms,
inheritance=inheritance,
reset=reset)
return True | python | def makedirs_perms(path,
owner=None,
grant_perms=None,
deny_perms=None,
inheritance=True,
reset=True):
'''
Set owner and permissions for each directory created.
Args:
path (str):
The full path to the directory.
owner (str):
The owner of the directory. If not passed, it will be the account
that created the directory, likely SYSTEM.
grant_perms (dict):
A dictionary containing the user/group and the basic permissions to
grant, ie: ``{'user': {'perms': 'basic_permission'}}``. You can also
set the ``applies_to`` setting here. The default is
``this_folder_subfolders_files``. Specify another ``applies_to``
setting like this:
.. code-block:: yaml
{'user': {'perms': 'full_control', 'applies_to': 'this_folder'}}
To set advanced permissions use a list for the ``perms`` parameter, ie:
.. code-block:: yaml
{'user': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder'}}
deny_perms (dict):
A dictionary containing the user/group and permissions to deny along
with the ``applies_to`` setting. Use the same format used for the
``grant_perms`` parameter. Remember, deny permissions supersede
grant permissions.
inheritance (bool):
If ``True`` the object will inherit permissions from the parent, if
``False``, inheritance will be disabled. Inheritance setting will
not apply to parent directories if they must be created
reset (bool):
If ``True`` the existing DACL will be cleared and replaced with the
settings defined in this function. If ``False``, new entries will be
appended to the existing DACL. Default is ``False``.
.. versionadded:: 2018.3.0
Returns:
bool: True if successful, otherwise raises an error
CLI Example:
.. code-block:: bash
# To grant the 'Users' group 'read & execute' permissions.
salt '*' file.makedirs_perms C:\\Temp\\ Administrators "{'Users': {'perms': 'read_execute'}}"
# Locally using salt call
salt-call file.makedirs_perms C:\\Temp\\ Administrators "{'Users': {'perms': 'read_execute', 'applies_to': 'this_folder_only'}}"
# Specify advanced attributes with a list
salt '*' file.makedirs_perms C:\\Temp\\ Administrators "{'jsnuffy': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder_files'}}"
'''
# Expand any environment variables
path = os.path.expanduser(path)
path = os.path.expandvars(path)
# Get parent directory (head)
head, tail = os.path.split(path)
# If tail is empty, split head
if not tail:
head, tail = os.path.split(head)
# If head and tail are defined and head is not there, recurse
if head and tail and not os.path.exists(head):
try:
# Create the directory here, set inherited True because this is a
# parent directory, the inheritance setting will only apply to the
# target directory. Reset will be False as we only want to reset
# the permissions on the target directory
makedirs_perms(
path=head,
owner=owner,
grant_perms=grant_perms,
deny_perms=deny_perms,
inheritance=True,
reset=False)
except OSError as exc:
# be happy if someone already created the path
if exc.errno != errno.EEXIST:
raise
if tail == os.curdir: # xxx/newdir/. exists if xxx/newdir exists
return {}
# Make the directory
mkdir(
path=path,
owner=owner,
grant_perms=grant_perms,
deny_perms=deny_perms,
inheritance=inheritance,
reset=reset)
return True | [
"def",
"makedirs_perms",
"(",
"path",
",",
"owner",
"=",
"None",
",",
"grant_perms",
"=",
"None",
",",
"deny_perms",
"=",
"None",
",",
"inheritance",
"=",
"True",
",",
"reset",
"=",
"True",
")",
":",
"# Expand any environment variables",
"path",
"=",
"os",
... | Set owner and permissions for each directory created.
Args:
path (str):
The full path to the directory.
owner (str):
The owner of the directory. If not passed, it will be the account
that created the directory, likely SYSTEM.
grant_perms (dict):
A dictionary containing the user/group and the basic permissions to
grant, ie: ``{'user': {'perms': 'basic_permission'}}``. You can also
set the ``applies_to`` setting here. The default is
``this_folder_subfolders_files``. Specify another ``applies_to``
setting like this:
.. code-block:: yaml
{'user': {'perms': 'full_control', 'applies_to': 'this_folder'}}
To set advanced permissions use a list for the ``perms`` parameter, ie:
.. code-block:: yaml
{'user': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder'}}
deny_perms (dict):
A dictionary containing the user/group and permissions to deny along
with the ``applies_to`` setting. Use the same format used for the
``grant_perms`` parameter. Remember, deny permissions supersede
grant permissions.
inheritance (bool):
If ``True`` the object will inherit permissions from the parent, if
``False``, inheritance will be disabled. Inheritance setting will
not apply to parent directories if they must be created
reset (bool):
If ``True`` the existing DACL will be cleared and replaced with the
settings defined in this function. If ``False``, new entries will be
appended to the existing DACL. Default is ``False``.
.. versionadded:: 2018.3.0
Returns:
bool: True if successful, otherwise raises an error
CLI Example:
.. code-block:: bash
# To grant the 'Users' group 'read & execute' permissions.
salt '*' file.makedirs_perms C:\\Temp\\ Administrators "{'Users': {'perms': 'read_execute'}}"
# Locally using salt call
salt-call file.makedirs_perms C:\\Temp\\ Administrators "{'Users': {'perms': 'read_execute', 'applies_to': 'this_folder_only'}}"
# Specify advanced attributes with a list
salt '*' file.makedirs_perms C:\\Temp\\ Administrators "{'jsnuffy': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder_files'}}" | [
"Set",
"owner",
"and",
"permissions",
"for",
"each",
"directory",
"created",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L1466-L1576 | train |
saltstack/salt | salt/modules/win_file.py | check_perms | def check_perms(path,
ret=None,
owner=None,
grant_perms=None,
deny_perms=None,
inheritance=True,
reset=False):
'''
Check owner and permissions for the passed directory. This function checks
the permissions and sets them, returning the changes made. Used by the file
state to populate the return dict
Args:
path (str):
The full path to the directory.
ret (dict):
A dictionary to append changes to and return. If not passed, will
create a new dictionary to return.
owner (str):
The owner to set for the directory.
grant_perms (dict):
A dictionary containing the user/group and the basic permissions to
check/grant, ie: ``{'user': {'perms': 'basic_permission'}}``.
Default is ``None``.
deny_perms (dict):
A dictionary containing the user/group and permissions to
check/deny. Default is ``None``.
inheritance (bool):
``True will check if inheritance is enabled and enable it. ``False``
will check if inheritance is disabled and disable it. Default is
``True``.
reset (bool):
``True`` will show what permissions will be removed by resetting the
DACL. ``False`` will do nothing. Default is ``False``.
Returns:
dict: A dictionary of changes that have been made
CLI Example:
.. code-block:: bash
# To see changes to ``C:\\Temp`` if the 'Users' group is given 'read & execute' permissions.
salt '*' file.check_perms C:\\Temp\\ {} Administrators "{'Users': {'perms': 'read_execute'}}"
# Locally using salt call
salt-call file.check_perms C:\\Temp\\ {} Administrators "{'Users': {'perms': 'read_execute', 'applies_to': 'this_folder_only'}}"
# Specify advanced attributes with a list
salt '*' file.check_perms C:\\Temp\\ {} Administrators "{'jsnuffy': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'files_only'}}"
'''
if not os.path.exists(path):
raise CommandExecutionError('Path not found: {0}'.format(path))
path = os.path.expanduser(path)
return __utils__['dacl.check_perms'](obj_name=path,
obj_type='file',
ret=ret,
owner=owner,
grant_perms=grant_perms,
deny_perms=deny_perms,
inheritance=inheritance,
reset=reset) | python | def check_perms(path,
ret=None,
owner=None,
grant_perms=None,
deny_perms=None,
inheritance=True,
reset=False):
'''
Check owner and permissions for the passed directory. This function checks
the permissions and sets them, returning the changes made. Used by the file
state to populate the return dict
Args:
path (str):
The full path to the directory.
ret (dict):
A dictionary to append changes to and return. If not passed, will
create a new dictionary to return.
owner (str):
The owner to set for the directory.
grant_perms (dict):
A dictionary containing the user/group and the basic permissions to
check/grant, ie: ``{'user': {'perms': 'basic_permission'}}``.
Default is ``None``.
deny_perms (dict):
A dictionary containing the user/group and permissions to
check/deny. Default is ``None``.
inheritance (bool):
``True will check if inheritance is enabled and enable it. ``False``
will check if inheritance is disabled and disable it. Default is
``True``.
reset (bool):
``True`` will show what permissions will be removed by resetting the
DACL. ``False`` will do nothing. Default is ``False``.
Returns:
dict: A dictionary of changes that have been made
CLI Example:
.. code-block:: bash
# To see changes to ``C:\\Temp`` if the 'Users' group is given 'read & execute' permissions.
salt '*' file.check_perms C:\\Temp\\ {} Administrators "{'Users': {'perms': 'read_execute'}}"
# Locally using salt call
salt-call file.check_perms C:\\Temp\\ {} Administrators "{'Users': {'perms': 'read_execute', 'applies_to': 'this_folder_only'}}"
# Specify advanced attributes with a list
salt '*' file.check_perms C:\\Temp\\ {} Administrators "{'jsnuffy': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'files_only'}}"
'''
if not os.path.exists(path):
raise CommandExecutionError('Path not found: {0}'.format(path))
path = os.path.expanduser(path)
return __utils__['dacl.check_perms'](obj_name=path,
obj_type='file',
ret=ret,
owner=owner,
grant_perms=grant_perms,
deny_perms=deny_perms,
inheritance=inheritance,
reset=reset) | [
"def",
"check_perms",
"(",
"path",
",",
"ret",
"=",
"None",
",",
"owner",
"=",
"None",
",",
"grant_perms",
"=",
"None",
",",
"deny_perms",
"=",
"None",
",",
"inheritance",
"=",
"True",
",",
"reset",
"=",
"False",
")",
":",
"if",
"not",
"os",
".",
"... | Check owner and permissions for the passed directory. This function checks
the permissions and sets them, returning the changes made. Used by the file
state to populate the return dict
Args:
path (str):
The full path to the directory.
ret (dict):
A dictionary to append changes to and return. If not passed, will
create a new dictionary to return.
owner (str):
The owner to set for the directory.
grant_perms (dict):
A dictionary containing the user/group and the basic permissions to
check/grant, ie: ``{'user': {'perms': 'basic_permission'}}``.
Default is ``None``.
deny_perms (dict):
A dictionary containing the user/group and permissions to
check/deny. Default is ``None``.
inheritance (bool):
``True will check if inheritance is enabled and enable it. ``False``
will check if inheritance is disabled and disable it. Default is
``True``.
reset (bool):
``True`` will show what permissions will be removed by resetting the
DACL. ``False`` will do nothing. Default is ``False``.
Returns:
dict: A dictionary of changes that have been made
CLI Example:
.. code-block:: bash
# To see changes to ``C:\\Temp`` if the 'Users' group is given 'read & execute' permissions.
salt '*' file.check_perms C:\\Temp\\ {} Administrators "{'Users': {'perms': 'read_execute'}}"
# Locally using salt call
salt-call file.check_perms C:\\Temp\\ {} Administrators "{'Users': {'perms': 'read_execute', 'applies_to': 'this_folder_only'}}"
# Specify advanced attributes with a list
salt '*' file.check_perms C:\\Temp\\ {} Administrators "{'jsnuffy': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'files_only'}}" | [
"Check",
"owner",
"and",
"permissions",
"for",
"the",
"passed",
"directory",
".",
"This",
"function",
"checks",
"the",
"permissions",
"and",
"sets",
"them",
"returning",
"the",
"changes",
"made",
".",
"Used",
"by",
"the",
"file",
"state",
"to",
"populate",
"... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L1579-L1649 | train |
saltstack/salt | salt/modules/win_file.py | set_perms | def set_perms(path,
grant_perms=None,
deny_perms=None,
inheritance=True,
reset=False):
'''
Set permissions for the given path
Args:
path (str):
The full path to the directory.
grant_perms (dict):
A dictionary containing the user/group and the basic permissions to
grant, ie: ``{'user': {'perms': 'basic_permission'}}``. You can also
set the ``applies_to`` setting here. The default for ``applise_to``
is ``this_folder_subfolders_files``. Specify another ``applies_to``
setting like this:
.. code-block:: yaml
{'user': {'perms': 'full_control', 'applies_to': 'this_folder'}}
To set advanced permissions use a list for the ``perms`` parameter,
ie:
.. code-block:: yaml
{'user': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder'}}
To see a list of available attributes and applies to settings see
the documentation for salt.utils.win_dacl.
A value of ``None`` will make no changes to the ``grant`` portion of
the DACL. Default is ``None``.
deny_perms (dict):
A dictionary containing the user/group and permissions to deny along
with the ``applies_to`` setting. Use the same format used for the
``grant_perms`` parameter. Remember, deny permissions supersede
grant permissions.
A value of ``None`` will make no changes to the ``deny`` portion of
the DACL. Default is ``None``.
inheritance (bool):
If ``True`` the object will inherit permissions from the parent, if
``False``, inheritance will be disabled. Inheritance setting will
not apply to parent directories if they must be created. Default is
``False``.
reset (bool):
If ``True`` the existing DCL will be cleared and replaced with the
settings defined in this function. If ``False``, new entries will be
appended to the existing DACL. Default is ``False``.
.. versionadded:: 2018.3.0
Returns:
bool: True if successful
Raises:
CommandExecutionError: If unsuccessful
CLI Example:
.. code-block:: bash
# To grant the 'Users' group 'read & execute' permissions.
salt '*' file.set_perms C:\\Temp\\ "{'Users': {'perms': 'read_execute'}}"
# Locally using salt call
salt-call file.set_perms C:\\Temp\\ "{'Users': {'perms': 'read_execute', 'applies_to': 'this_folder_only'}}"
# Specify advanced attributes with a list
salt '*' file.set_perms C:\\Temp\\ "{'jsnuffy': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder_only'}}"
'''
return __utils__['dacl.set_perms'](obj_name=path,
obj_type='file',
grant_perms=grant_perms,
deny_perms=deny_perms,
inheritance=inheritance,
reset=reset) | python | def set_perms(path,
grant_perms=None,
deny_perms=None,
inheritance=True,
reset=False):
'''
Set permissions for the given path
Args:
path (str):
The full path to the directory.
grant_perms (dict):
A dictionary containing the user/group and the basic permissions to
grant, ie: ``{'user': {'perms': 'basic_permission'}}``. You can also
set the ``applies_to`` setting here. The default for ``applise_to``
is ``this_folder_subfolders_files``. Specify another ``applies_to``
setting like this:
.. code-block:: yaml
{'user': {'perms': 'full_control', 'applies_to': 'this_folder'}}
To set advanced permissions use a list for the ``perms`` parameter,
ie:
.. code-block:: yaml
{'user': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder'}}
To see a list of available attributes and applies to settings see
the documentation for salt.utils.win_dacl.
A value of ``None`` will make no changes to the ``grant`` portion of
the DACL. Default is ``None``.
deny_perms (dict):
A dictionary containing the user/group and permissions to deny along
with the ``applies_to`` setting. Use the same format used for the
``grant_perms`` parameter. Remember, deny permissions supersede
grant permissions.
A value of ``None`` will make no changes to the ``deny`` portion of
the DACL. Default is ``None``.
inheritance (bool):
If ``True`` the object will inherit permissions from the parent, if
``False``, inheritance will be disabled. Inheritance setting will
not apply to parent directories if they must be created. Default is
``False``.
reset (bool):
If ``True`` the existing DCL will be cleared and replaced with the
settings defined in this function. If ``False``, new entries will be
appended to the existing DACL. Default is ``False``.
.. versionadded:: 2018.3.0
Returns:
bool: True if successful
Raises:
CommandExecutionError: If unsuccessful
CLI Example:
.. code-block:: bash
# To grant the 'Users' group 'read & execute' permissions.
salt '*' file.set_perms C:\\Temp\\ "{'Users': {'perms': 'read_execute'}}"
# Locally using salt call
salt-call file.set_perms C:\\Temp\\ "{'Users': {'perms': 'read_execute', 'applies_to': 'this_folder_only'}}"
# Specify advanced attributes with a list
salt '*' file.set_perms C:\\Temp\\ "{'jsnuffy': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder_only'}}"
'''
return __utils__['dacl.set_perms'](obj_name=path,
obj_type='file',
grant_perms=grant_perms,
deny_perms=deny_perms,
inheritance=inheritance,
reset=reset) | [
"def",
"set_perms",
"(",
"path",
",",
"grant_perms",
"=",
"None",
",",
"deny_perms",
"=",
"None",
",",
"inheritance",
"=",
"True",
",",
"reset",
"=",
"False",
")",
":",
"return",
"__utils__",
"[",
"'dacl.set_perms'",
"]",
"(",
"obj_name",
"=",
"path",
",... | Set permissions for the given path
Args:
path (str):
The full path to the directory.
grant_perms (dict):
A dictionary containing the user/group and the basic permissions to
grant, ie: ``{'user': {'perms': 'basic_permission'}}``. You can also
set the ``applies_to`` setting here. The default for ``applise_to``
is ``this_folder_subfolders_files``. Specify another ``applies_to``
setting like this:
.. code-block:: yaml
{'user': {'perms': 'full_control', 'applies_to': 'this_folder'}}
To set advanced permissions use a list for the ``perms`` parameter,
ie:
.. code-block:: yaml
{'user': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder'}}
To see a list of available attributes and applies to settings see
the documentation for salt.utils.win_dacl.
A value of ``None`` will make no changes to the ``grant`` portion of
the DACL. Default is ``None``.
deny_perms (dict):
A dictionary containing the user/group and permissions to deny along
with the ``applies_to`` setting. Use the same format used for the
``grant_perms`` parameter. Remember, deny permissions supersede
grant permissions.
A value of ``None`` will make no changes to the ``deny`` portion of
the DACL. Default is ``None``.
inheritance (bool):
If ``True`` the object will inherit permissions from the parent, if
``False``, inheritance will be disabled. Inheritance setting will
not apply to parent directories if they must be created. Default is
``False``.
reset (bool):
If ``True`` the existing DCL will be cleared and replaced with the
settings defined in this function. If ``False``, new entries will be
appended to the existing DACL. Default is ``False``.
.. versionadded:: 2018.3.0
Returns:
bool: True if successful
Raises:
CommandExecutionError: If unsuccessful
CLI Example:
.. code-block:: bash
# To grant the 'Users' group 'read & execute' permissions.
salt '*' file.set_perms C:\\Temp\\ "{'Users': {'perms': 'read_execute'}}"
# Locally using salt call
salt-call file.set_perms C:\\Temp\\ "{'Users': {'perms': 'read_execute', 'applies_to': 'this_folder_only'}}"
# Specify advanced attributes with a list
salt '*' file.set_perms C:\\Temp\\ "{'jsnuffy': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'this_folder_only'}}" | [
"Set",
"permissions",
"for",
"the",
"given",
"path"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_file.py#L1652-L1735 | train |
saltstack/salt | salt/beacons/haproxy.py | validate | def validate(config):
'''
Validate the beacon configuration
'''
if not isinstance(config, list):
return False, ('Configuration for haproxy beacon must '
'be a list.')
else:
_config = {}
list(map(_config.update, config))
if 'backends' not in _config:
return False, ('Configuration for haproxy beacon '
'requires backends.')
else:
if not isinstance(_config['backends'], dict):
return False, ('Backends for haproxy beacon '
'must be a dictionary.')
else:
for backend in _config['backends']:
log.debug('_config %s', _config['backends'][backend])
if 'servers' not in _config['backends'][backend]:
return False, ('Backends for haproxy beacon '
'require servers.')
else:
_servers = _config['backends'][backend]['servers']
if not isinstance(_servers, list):
return False, ('Servers for haproxy beacon '
'must be a list.')
return True, 'Valid beacon configuration' | python | def validate(config):
'''
Validate the beacon configuration
'''
if not isinstance(config, list):
return False, ('Configuration for haproxy beacon must '
'be a list.')
else:
_config = {}
list(map(_config.update, config))
if 'backends' not in _config:
return False, ('Configuration for haproxy beacon '
'requires backends.')
else:
if not isinstance(_config['backends'], dict):
return False, ('Backends for haproxy beacon '
'must be a dictionary.')
else:
for backend in _config['backends']:
log.debug('_config %s', _config['backends'][backend])
if 'servers' not in _config['backends'][backend]:
return False, ('Backends for haproxy beacon '
'require servers.')
else:
_servers = _config['backends'][backend]['servers']
if not isinstance(_servers, list):
return False, ('Servers for haproxy beacon '
'must be a list.')
return True, 'Valid beacon configuration' | [
"def",
"validate",
"(",
"config",
")",
":",
"if",
"not",
"isinstance",
"(",
"config",
",",
"list",
")",
":",
"return",
"False",
",",
"(",
"'Configuration for haproxy beacon must '",
"'be a list.'",
")",
"else",
":",
"_config",
"=",
"{",
"}",
"list",
"(",
"... | Validate the beacon configuration | [
"Validate",
"the",
"beacon",
"configuration"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/haproxy.py#L30-L59 | train |
saltstack/salt | salt/beacons/haproxy.py | beacon | def beacon(config):
'''
Check if current number of sessions of a server for a specific haproxy backend
is over a defined threshold.
.. code-block:: yaml
beacons:
haproxy:
- backends:
www-backend:
threshold: 45
servers:
- web1
- web2
- interval: 120
'''
ret = []
_config = {}
list(map(_config.update, config))
for backend in _config.get('backends', ()):
backend_config = _config['backends'][backend]
threshold = backend_config['threshold']
for server in backend_config['servers']:
scur = __salt__['haproxy.get_sessions'](server, backend)
if scur:
if int(scur) > int(threshold):
_server = {'server': server,
'scur': scur,
'threshold': threshold,
}
log.debug('Emit because %s > %s'
' for %s in %s', scur,
threshold,
server,
backend)
ret.append(_server)
return ret | python | def beacon(config):
'''
Check if current number of sessions of a server for a specific haproxy backend
is over a defined threshold.
.. code-block:: yaml
beacons:
haproxy:
- backends:
www-backend:
threshold: 45
servers:
- web1
- web2
- interval: 120
'''
ret = []
_config = {}
list(map(_config.update, config))
for backend in _config.get('backends', ()):
backend_config = _config['backends'][backend]
threshold = backend_config['threshold']
for server in backend_config['servers']:
scur = __salt__['haproxy.get_sessions'](server, backend)
if scur:
if int(scur) > int(threshold):
_server = {'server': server,
'scur': scur,
'threshold': threshold,
}
log.debug('Emit because %s > %s'
' for %s in %s', scur,
threshold,
server,
backend)
ret.append(_server)
return ret | [
"def",
"beacon",
"(",
"config",
")",
":",
"ret",
"=",
"[",
"]",
"_config",
"=",
"{",
"}",
"list",
"(",
"map",
"(",
"_config",
".",
"update",
",",
"config",
")",
")",
"for",
"backend",
"in",
"_config",
".",
"get",
"(",
"'backends'",
",",
"(",
")",... | Check if current number of sessions of a server for a specific haproxy backend
is over a defined threshold.
.. code-block:: yaml
beacons:
haproxy:
- backends:
www-backend:
threshold: 45
servers:
- web1
- web2
- interval: 120 | [
"Check",
"if",
"current",
"number",
"of",
"sessions",
"of",
"a",
"server",
"for",
"a",
"specific",
"haproxy",
"backend",
"is",
"over",
"a",
"defined",
"threshold",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/haproxy.py#L62-L101 | train |
saltstack/salt | salt/modules/boto_iot.py | thing_type_exists | def thing_type_exists(thingTypeName,
region=None, key=None, keyid=None, profile=None):
'''
Given a thing type name, check to see if the given thing type exists
Returns True if the given thing type exists and returns False if the
given thing type does not exist.
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt myminion boto_iot.thing_type_exists mythingtype
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
res = conn.describe_thing_type(thingTypeName=thingTypeName)
if res.get('thingTypeName'):
return {'exists': True}
else:
return {'exists': False}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'ResourceNotFoundException':
return {'exists': False}
return {'error': err} | python | def thing_type_exists(thingTypeName,
region=None, key=None, keyid=None, profile=None):
'''
Given a thing type name, check to see if the given thing type exists
Returns True if the given thing type exists and returns False if the
given thing type does not exist.
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt myminion boto_iot.thing_type_exists mythingtype
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
res = conn.describe_thing_type(thingTypeName=thingTypeName)
if res.get('thingTypeName'):
return {'exists': True}
else:
return {'exists': False}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'ResourceNotFoundException':
return {'exists': False}
return {'error': err} | [
"def",
"thing_type_exists",
"(",
"thingTypeName",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"... | Given a thing type name, check to see if the given thing type exists
Returns True if the given thing type exists and returns False if the
given thing type does not exist.
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt myminion boto_iot.thing_type_exists mythingtype | [
"Given",
"a",
"thing",
"type",
"name",
"check",
"to",
"see",
"if",
"the",
"given",
"thing",
"type",
"exists"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iot.py#L101-L130 | train |
saltstack/salt | salt/modules/boto_iot.py | describe_thing_type | def describe_thing_type(thingTypeName,
region=None, key=None, keyid=None, profile=None):
'''
Given a thing type name describe its properties.
Returns a dictionary of interesting properties.
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt myminion boto_iot.describe_thing_type mythingtype
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
res = conn.describe_thing_type(thingTypeName=thingTypeName)
if res:
res.pop('ResponseMetadata', None)
thingTypeMetadata = res.get('thingTypeMetadata')
if thingTypeMetadata:
for dtype in ('creationDate', 'deprecationDate'):
dval = thingTypeMetadata.get(dtype)
if dval and isinstance(dval, datetime.date):
thingTypeMetadata[dtype] = '{0}'.format(dval)
return {'thing_type': res}
else:
return {'thing_type': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'ResourceNotFoundException':
return {'thing_type': None}
return {'error': err} | python | def describe_thing_type(thingTypeName,
region=None, key=None, keyid=None, profile=None):
'''
Given a thing type name describe its properties.
Returns a dictionary of interesting properties.
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt myminion boto_iot.describe_thing_type mythingtype
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
res = conn.describe_thing_type(thingTypeName=thingTypeName)
if res:
res.pop('ResponseMetadata', None)
thingTypeMetadata = res.get('thingTypeMetadata')
if thingTypeMetadata:
for dtype in ('creationDate', 'deprecationDate'):
dval = thingTypeMetadata.get(dtype)
if dval and isinstance(dval, datetime.date):
thingTypeMetadata[dtype] = '{0}'.format(dval)
return {'thing_type': res}
else:
return {'thing_type': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'ResourceNotFoundException':
return {'thing_type': None}
return {'error': err} | [
"def",
"describe_thing_type",
"(",
"thingTypeName",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
... | Given a thing type name describe its properties.
Returns a dictionary of interesting properties.
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt myminion boto_iot.describe_thing_type mythingtype | [
"Given",
"a",
"thing",
"type",
"name",
"describe",
"its",
"properties",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iot.py#L133-L167 | train |
saltstack/salt | salt/modules/boto_iot.py | create_thing_type | def create_thing_type(thingTypeName, thingTypeDescription,
searchableAttributesList, region=None, key=None,
keyid=None, profile=None):
'''
Given a valid config, create a thing type.
Returns {created: true} if the thing type was created and returns
{created: False} if the thing type was not created.
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt myminion boto_iot.create_thing_type mythingtype \\
thingtype_description_string '["searchable_attr_1", "searchable_attr_2"]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
thingTypeProperties = dict(
thingTypeDescription=thingTypeDescription,
searchableAttributes=searchableAttributesList
)
thingtype = conn.create_thing_type(
thingTypeName=thingTypeName,
thingTypeProperties=thingTypeProperties
)
if thingtype:
log.info('The newly created thing type ARN is %s', thingtype['thingTypeArn'])
return {'created': True, 'thingTypeArn': thingtype['thingTypeArn']}
else:
log.warning('thing type was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)} | python | def create_thing_type(thingTypeName, thingTypeDescription,
searchableAttributesList, region=None, key=None,
keyid=None, profile=None):
'''
Given a valid config, create a thing type.
Returns {created: true} if the thing type was created and returns
{created: False} if the thing type was not created.
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt myminion boto_iot.create_thing_type mythingtype \\
thingtype_description_string '["searchable_attr_1", "searchable_attr_2"]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
thingTypeProperties = dict(
thingTypeDescription=thingTypeDescription,
searchableAttributes=searchableAttributesList
)
thingtype = conn.create_thing_type(
thingTypeName=thingTypeName,
thingTypeProperties=thingTypeProperties
)
if thingtype:
log.info('The newly created thing type ARN is %s', thingtype['thingTypeArn'])
return {'created': True, 'thingTypeArn': thingtype['thingTypeArn']}
else:
log.warning('thing type was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"create_thing_type",
"(",
"thingTypeName",
",",
"thingTypeDescription",
",",
"searchableAttributesList",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
... | Given a valid config, create a thing type.
Returns {created: true} if the thing type was created and returns
{created: False} if the thing type was not created.
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt myminion boto_iot.create_thing_type mythingtype \\
thingtype_description_string '["searchable_attr_1", "searchable_attr_2"]' | [
"Given",
"a",
"valid",
"config",
"create",
"a",
"thing",
"type",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iot.py#L170-L209 | train |
saltstack/salt | salt/modules/boto_iot.py | deprecate_thing_type | def deprecate_thing_type(thingTypeName, undoDeprecate=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a thing type name, deprecate it when undoDeprecate is False
and undeprecate it when undoDeprecate is True.
Returns {deprecated: true} if the thing type was deprecated and returns
{deprecated: false} if the thing type was not deprecated.
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt myminion boto_iot.deprecate_thing_type mythingtype
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.deprecate_thing_type(
thingTypeName=thingTypeName,
undoDeprecate=undoDeprecate
)
deprecated = True if undoDeprecate is False else False
return {'deprecated': deprecated}
except ClientError as e:
return {'deprecated': False, 'error': __utils__['boto3.get_error'](e)} | python | def deprecate_thing_type(thingTypeName, undoDeprecate=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a thing type name, deprecate it when undoDeprecate is False
and undeprecate it when undoDeprecate is True.
Returns {deprecated: true} if the thing type was deprecated and returns
{deprecated: false} if the thing type was not deprecated.
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt myminion boto_iot.deprecate_thing_type mythingtype
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.deprecate_thing_type(
thingTypeName=thingTypeName,
undoDeprecate=undoDeprecate
)
deprecated = True if undoDeprecate is False else False
return {'deprecated': deprecated}
except ClientError as e:
return {'deprecated': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"deprecate_thing_type",
"(",
"thingTypeName",
",",
"undoDeprecate",
"=",
"False",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"... | Given a thing type name, deprecate it when undoDeprecate is False
and undeprecate it when undoDeprecate is True.
Returns {deprecated: true} if the thing type was deprecated and returns
{deprecated: false} if the thing type was not deprecated.
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt myminion boto_iot.deprecate_thing_type mythingtype | [
"Given",
"a",
"thing",
"type",
"name",
"deprecate",
"it",
"when",
"undoDeprecate",
"is",
"False",
"and",
"undeprecate",
"it",
"when",
"undoDeprecate",
"is",
"True",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iot.py#L212-L240 | train |
saltstack/salt | salt/modules/boto_iot.py | delete_thing_type | def delete_thing_type(thingTypeName,
region=None, key=None, keyid=None, profile=None):
'''
Given a thing type name, delete it.
Returns {deleted: true} if the thing type was deleted and returns
{deleted: false} if the thing type was not deleted.
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt myminion boto_iot.delete_thing_type mythingtype
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_thing_type(thingTypeName=thingTypeName)
return {'deleted': True}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'ResourceNotFoundException':
return {'deleted': True}
return {'deleted': False, 'error': err} | python | def delete_thing_type(thingTypeName,
region=None, key=None, keyid=None, profile=None):
'''
Given a thing type name, delete it.
Returns {deleted: true} if the thing type was deleted and returns
{deleted: false} if the thing type was not deleted.
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt myminion boto_iot.delete_thing_type mythingtype
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_thing_type(thingTypeName=thingTypeName)
return {'deleted': True}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'ResourceNotFoundException':
return {'deleted': True}
return {'deleted': False, 'error': err} | [
"def",
"delete_thing_type",
"(",
"thingTypeName",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"... | Given a thing type name, delete it.
Returns {deleted: true} if the thing type was deleted and returns
{deleted: false} if the thing type was not deleted.
.. versionadded:: 2016.11.0
CLI Example:
.. code-block:: bash
salt myminion boto_iot.delete_thing_type mythingtype | [
"Given",
"a",
"thing",
"type",
"name",
"delete",
"it",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iot.py#L243-L269 | train |
saltstack/salt | salt/modules/boto_iot.py | policy_exists | def policy_exists(policyName,
region=None, key=None, keyid=None, profile=None):
'''
Given a policy name, check to see if the given policy exists.
Returns True if the given policy exists and returns False if the given
policy does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.policy_exists mypolicy
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.get_policy(policyName=policyName)
return {'exists': True}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'ResourceNotFoundException':
return {'exists': False}
return {'error': err} | python | def policy_exists(policyName,
region=None, key=None, keyid=None, profile=None):
'''
Given a policy name, check to see if the given policy exists.
Returns True if the given policy exists and returns False if the given
policy does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.policy_exists mypolicy
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.get_policy(policyName=policyName)
return {'exists': True}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'ResourceNotFoundException':
return {'exists': False}
return {'error': err} | [
"def",
"policy_exists",
"(",
"policyName",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"... | Given a policy name, check to see if the given policy exists.
Returns True if the given policy exists and returns False if the given
policy does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.policy_exists mypolicy | [
"Given",
"a",
"policy",
"name",
"check",
"to",
"see",
"if",
"the",
"given",
"policy",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iot.py#L272-L296 | train |
saltstack/salt | salt/modules/boto_iot.py | create_policy | def create_policy(policyName, policyDocument,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create a policy.
Returns {created: true} if the policy was created and returns
{created: False} if the policy was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.create_policy my_policy \\
'{"Version":"2015-12-12",\\
"Statement":[{"Effect":"Allow",\\
"Action":["iot:Publish"],\\
"Resource":["arn:::::topic/foo/bar"]}]}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not isinstance(policyDocument, string_types):
policyDocument = salt.utils.json.dumps(policyDocument)
policy = conn.create_policy(policyName=policyName,
policyDocument=policyDocument)
if policy:
log.info('The newly created policy version is %s', policy['policyVersionId'])
return {'created': True, 'versionId': policy['policyVersionId']}
else:
log.warning('Policy was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)} | python | def create_policy(policyName, policyDocument,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create a policy.
Returns {created: true} if the policy was created and returns
{created: False} if the policy was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.create_policy my_policy \\
'{"Version":"2015-12-12",\\
"Statement":[{"Effect":"Allow",\\
"Action":["iot:Publish"],\\
"Resource":["arn:::::topic/foo/bar"]}]}'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
if not isinstance(policyDocument, string_types):
policyDocument = salt.utils.json.dumps(policyDocument)
policy = conn.create_policy(policyName=policyName,
policyDocument=policyDocument)
if policy:
log.info('The newly created policy version is %s', policy['policyVersionId'])
return {'created': True, 'versionId': policy['policyVersionId']}
else:
log.warning('Policy was not created')
return {'created': False}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"create_policy",
"(",
"policyName",
",",
"policyDocument",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",... | Given a valid config, create a policy.
Returns {created: true} if the policy was created and returns
{created: False} if the policy was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.create_policy my_policy \\
'{"Version":"2015-12-12",\\
"Statement":[{"Effect":"Allow",\\
"Action":["iot:Publish"],\\
"Resource":["arn:::::topic/foo/bar"]}]}' | [
"Given",
"a",
"valid",
"config",
"create",
"a",
"policy",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iot.py#L299-L333 | train |
saltstack/salt | salt/modules/boto_iot.py | describe_policy | def describe_policy(policyName,
region=None, key=None, keyid=None, profile=None):
'''
Given a policy name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.describe_policy mypolicy
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
policy = conn.get_policy(policyName=policyName)
if policy:
keys = ('policyName', 'policyArn', 'policyDocument',
'defaultVersionId')
return {'policy': dict([(k, policy.get(k)) for k in keys])}
else:
return {'policy': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'ResourceNotFoundException':
return {'policy': None}
return {'error': __utils__['boto3.get_error'](e)} | python | def describe_policy(policyName,
region=None, key=None, keyid=None, profile=None):
'''
Given a policy name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.describe_policy mypolicy
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
policy = conn.get_policy(policyName=policyName)
if policy:
keys = ('policyName', 'policyArn', 'policyDocument',
'defaultVersionId')
return {'policy': dict([(k, policy.get(k)) for k in keys])}
else:
return {'policy': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'ResourceNotFoundException':
return {'policy': None}
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"describe_policy",
"(",
"policyName",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
... | Given a policy name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.describe_policy mypolicy | [
"Given",
"a",
"policy",
"name",
"describe",
"its",
"properties",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iot.py#L360-L388 | train |
saltstack/salt | salt/modules/boto_iot.py | policy_version_exists | def policy_version_exists(policyName, policyVersionId,
region=None, key=None, keyid=None, profile=None):
'''
Given a policy name and version ID, check to see if the given policy version exists.
Returns True if the given policy version exists and returns False if the given
policy version does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.policy_version_exists mypolicy versionid
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
policy = conn.get_policy_version(policyName=policyName,
policyversionId=policyVersionId)
return {'exists': bool(policy)}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'ResourceNotFoundException':
return {'exists': False}
return {'error': __utils__['boto3.get_error'](e)} | python | def policy_version_exists(policyName, policyVersionId,
region=None, key=None, keyid=None, profile=None):
'''
Given a policy name and version ID, check to see if the given policy version exists.
Returns True if the given policy version exists and returns False if the given
policy version does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.policy_version_exists mypolicy versionid
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
policy = conn.get_policy_version(policyName=policyName,
policyversionId=policyVersionId)
return {'exists': bool(policy)}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'ResourceNotFoundException':
return {'exists': False}
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"policy_version_exists",
"(",
"policyName",
",",
"policyVersionId",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
... | Given a policy name and version ID, check to see if the given policy version exists.
Returns True if the given policy version exists and returns False if the given
policy version does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.policy_version_exists mypolicy versionid | [
"Given",
"a",
"policy",
"name",
"and",
"version",
"ID",
"check",
"to",
"see",
"if",
"the",
"given",
"policy",
"version",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iot.py#L391-L416 | train |
saltstack/salt | salt/modules/boto_iot.py | delete_policy_version | def delete_policy_version(policyName, policyVersionId,
region=None, key=None, keyid=None, profile=None):
'''
Given a policy name and version, delete it.
Returns {deleted: true} if the policy version was deleted and returns
{deleted: false} if the policy version was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.delete_policy_version mypolicy version
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_policy_version(policyName=policyName,
policyVersionId=policyVersionId)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)} | python | def delete_policy_version(policyName, policyVersionId,
region=None, key=None, keyid=None, profile=None):
'''
Given a policy name and version, delete it.
Returns {deleted: true} if the policy version was deleted and returns
{deleted: false} if the policy version was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.delete_policy_version mypolicy version
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_policy_version(policyName=policyName,
policyVersionId=policyVersionId)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"delete_policy_version",
"(",
"policyName",
",",
"policyVersionId",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
... | Given a policy name and version, delete it.
Returns {deleted: true} if the policy version was deleted and returns
{deleted: false} if the policy version was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.delete_policy_version mypolicy version | [
"Given",
"a",
"policy",
"name",
"and",
"version",
"delete",
"it",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iot.py#L454-L476 | train |
saltstack/salt | salt/modules/boto_iot.py | describe_policy_version | def describe_policy_version(policyName, policyVersionId,
region=None, key=None, keyid=None, profile=None):
'''
Given a policy name and version describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.describe_policy_version mypolicy version
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
policy = conn.get_policy_version(policyName=policyName,
policyVersionId=policyVersionId)
if policy:
keys = ('policyName', 'policyArn', 'policyDocument',
'policyVersionId', 'isDefaultVersion')
return {'policy': dict([(k, policy.get(k)) for k in keys])}
else:
return {'policy': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'ResourceNotFoundException':
return {'policy': None}
return {'error': __utils__['boto3.get_error'](e)} | python | def describe_policy_version(policyName, policyVersionId,
region=None, key=None, keyid=None, profile=None):
'''
Given a policy name and version describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.describe_policy_version mypolicy version
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
policy = conn.get_policy_version(policyName=policyName,
policyVersionId=policyVersionId)
if policy:
keys = ('policyName', 'policyArn', 'policyDocument',
'policyVersionId', 'isDefaultVersion')
return {'policy': dict([(k, policy.get(k)) for k in keys])}
else:
return {'policy': None}
except ClientError as e:
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'ResourceNotFoundException':
return {'policy': None}
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"describe_policy_version",
"(",
"policyName",
",",
"policyVersionId",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
... | Given a policy name and version describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.describe_policy_version mypolicy version | [
"Given",
"a",
"policy",
"name",
"and",
"version",
"describe",
"its",
"properties",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iot.py#L479-L508 | train |
saltstack/salt | salt/modules/boto_iot.py | list_policies | def list_policies(region=None, key=None, keyid=None, profile=None):
'''
List all policies
Returns list of policies
CLI Example:
.. code-block:: bash
salt myminion boto_iot.list_policies
Example Return:
.. code-block:: yaml
policies:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
policies = []
for ret in __utils__['boto3.paged_call'](conn.list_policies,
marker_flag='nextMarker',
marker_arg='marker'):
policies.extend(ret['policies'])
if not bool(policies):
log.warning('No policies found')
return {'policies': policies}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | python | def list_policies(region=None, key=None, keyid=None, profile=None):
'''
List all policies
Returns list of policies
CLI Example:
.. code-block:: bash
salt myminion boto_iot.list_policies
Example Return:
.. code-block:: yaml
policies:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
policies = []
for ret in __utils__['boto3.paged_call'](conn.list_policies,
marker_flag='nextMarker',
marker_arg='marker'):
policies.extend(ret['policies'])
if not bool(policies):
log.warning('No policies found')
return {'policies': policies}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"list_policies",
"(",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",... | List all policies
Returns list of policies
CLI Example:
.. code-block:: bash
salt myminion boto_iot.list_policies
Example Return:
.. code-block:: yaml
policies:
- {...}
- {...} | [
"List",
"all",
"policies"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iot.py#L511-L543 | train |
saltstack/salt | salt/modules/boto_iot.py | list_policy_versions | def list_policy_versions(policyName,
region=None, key=None, keyid=None, profile=None):
'''
List the versions available for the given policy.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.list_policy_versions mypolicy
Example Return:
.. code-block:: yaml
policyVersions:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
vers = []
for ret in __utils__['boto3.paged_call'](conn.list_policy_versions,
marker_flag='nextMarker',
marker_arg='marker',
policyName=policyName):
vers.extend(ret['policyVersions'])
if not bool(vers):
log.warning('No versions found')
return {'policyVersions': vers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | python | def list_policy_versions(policyName,
region=None, key=None, keyid=None, profile=None):
'''
List the versions available for the given policy.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.list_policy_versions mypolicy
Example Return:
.. code-block:: yaml
policyVersions:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
vers = []
for ret in __utils__['boto3.paged_call'](conn.list_policy_versions,
marker_flag='nextMarker',
marker_arg='marker',
policyName=policyName):
vers.extend(ret['policyVersions'])
if not bool(vers):
log.warning('No versions found')
return {'policyVersions': vers}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"list_policy_versions",
"(",
"policyName",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"... | List the versions available for the given policy.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.list_policy_versions mypolicy
Example Return:
.. code-block:: yaml
policyVersions:
- {...}
- {...} | [
"List",
"the",
"versions",
"available",
"for",
"the",
"given",
"policy",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iot.py#L546-L578 | train |
saltstack/salt | salt/modules/boto_iot.py | topic_rule_exists | def topic_rule_exists(ruleName,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name, check to see if the given rule exists.
Returns True if the given rule exists and returns False if the given
rule does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.topic_rule_exists myrule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
rule = conn.get_topic_rule(ruleName=ruleName)
return {'exists': True}
except ClientError as e:
# Nonexistent rules show up as unauthorized exceptions. It's unclear how
# to distinguish this from a real authorization exception. In practical
# use, it's more useful to assume lack of existence than to assume a
# genuine authorization problem; authorization problems should not be
# the common case.
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'UnauthorizedException':
return {'exists': False}
return {'error': __utils__['boto3.get_error'](e)} | python | def topic_rule_exists(ruleName,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name, check to see if the given rule exists.
Returns True if the given rule exists and returns False if the given
rule does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.topic_rule_exists myrule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
rule = conn.get_topic_rule(ruleName=ruleName)
return {'exists': True}
except ClientError as e:
# Nonexistent rules show up as unauthorized exceptions. It's unclear how
# to distinguish this from a real authorization exception. In practical
# use, it's more useful to assume lack of existence than to assume a
# genuine authorization problem; authorization problems should not be
# the common case.
err = __utils__['boto3.get_error'](e)
if e.response.get('Error', {}).get('Code') == 'UnauthorizedException':
return {'exists': False}
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"topic_rule_exists",
"(",
"ruleName",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
... | Given a rule name, check to see if the given rule exists.
Returns True if the given rule exists and returns False if the given
rule does not exist.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.topic_rule_exists myrule | [
"Given",
"a",
"rule",
"name",
"check",
"to",
"see",
"if",
"the",
"given",
"rule",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iot.py#L694-L723 | train |
saltstack/salt | salt/modules/boto_iot.py | create_topic_rule | def create_topic_rule(ruleName, sql, actions, description,
ruleDisabled=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create a topic rule.
Returns {created: true} if the rule was created and returns
{created: False} if the rule was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.create_topic_rule my_rule "SELECT * FROM 'some/thing'" \\
'[{"lambda":{"functionArn":"arn:::::something"}},{"sns":{\\
"targetArn":"arn:::::something","roleArn":"arn:::::something"}}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.create_topic_rule(ruleName=ruleName,
topicRulePayload={
'sql': sql,
'description': description,
'actions': actions,
'ruleDisabled': ruleDisabled
})
return {'created': True}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)} | python | def create_topic_rule(ruleName, sql, actions, description,
ruleDisabled=False,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid config, create a topic rule.
Returns {created: true} if the rule was created and returns
{created: False} if the rule was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.create_topic_rule my_rule "SELECT * FROM 'some/thing'" \\
'[{"lambda":{"functionArn":"arn:::::something"}},{"sns":{\\
"targetArn":"arn:::::something","roleArn":"arn:::::something"}}]'
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.create_topic_rule(ruleName=ruleName,
topicRulePayload={
'sql': sql,
'description': description,
'actions': actions,
'ruleDisabled': ruleDisabled
})
return {'created': True}
except ClientError as e:
return {'created': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"create_topic_rule",
"(",
"ruleName",
",",
"sql",
",",
"actions",
",",
"description",
",",
"ruleDisabled",
"=",
"False",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try"... | Given a valid config, create a topic rule.
Returns {created: true} if the rule was created and returns
{created: False} if the rule was not created.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.create_topic_rule my_rule "SELECT * FROM 'some/thing'" \\
'[{"lambda":{"functionArn":"arn:::::something"}},{"sns":{\\
"targetArn":"arn:::::something","roleArn":"arn:::::something"}}]' | [
"Given",
"a",
"valid",
"config",
"create",
"a",
"topic",
"rule",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iot.py#L726-L756 | train |
saltstack/salt | salt/modules/boto_iot.py | delete_topic_rule | def delete_topic_rule(ruleName,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name, delete it.
Returns {deleted: true} if the rule was deleted and returns
{deleted: false} if the rule was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.delete_rule myrule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_topic_rule(ruleName=ruleName)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)} | python | def delete_topic_rule(ruleName,
region=None, key=None, keyid=None, profile=None):
'''
Given a rule name, delete it.
Returns {deleted: true} if the rule was deleted and returns
{deleted: false} if the rule was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.delete_rule myrule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
conn.delete_topic_rule(ruleName=ruleName)
return {'deleted': True}
except ClientError as e:
return {'deleted': False, 'error': __utils__['boto3.get_error'](e)} | [
"def",
"delete_topic_rule",
"(",
"ruleName",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
... | Given a rule name, delete it.
Returns {deleted: true} if the rule was deleted and returns
{deleted: false} if the rule was not deleted.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.delete_rule myrule | [
"Given",
"a",
"rule",
"name",
"delete",
"it",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iot.py#L792-L813 | train |
saltstack/salt | salt/modules/boto_iot.py | describe_topic_rule | def describe_topic_rule(ruleName,
region=None, key=None, keyid=None, profile=None):
'''
Given a topic rule name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.describe_topic_rule myrule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
rule = conn.get_topic_rule(ruleName=ruleName)
if rule and 'rule' in rule:
rule = rule['rule']
keys = ('ruleName', 'sql', 'description',
'actions', 'ruleDisabled')
return {'rule': dict([(k, rule.get(k)) for k in keys])}
else:
return {'rule': None}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | python | def describe_topic_rule(ruleName,
region=None, key=None, keyid=None, profile=None):
'''
Given a topic rule name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.describe_topic_rule myrule
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
rule = conn.get_topic_rule(ruleName=ruleName)
if rule and 'rule' in rule:
rule = rule['rule']
keys = ('ruleName', 'sql', 'description',
'actions', 'ruleDisabled')
return {'rule': dict([(k, rule.get(k)) for k in keys])}
else:
return {'rule': None}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"describe_topic_rule",
"(",
"ruleName",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",... | Given a topic rule name describe its properties.
Returns a dictionary of interesting properties.
CLI Example:
.. code-block:: bash
salt myminion boto_iot.describe_topic_rule myrule | [
"Given",
"a",
"topic",
"rule",
"name",
"describe",
"its",
"properties",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iot.py#L816-L842 | train |
saltstack/salt | salt/modules/boto_iot.py | list_topic_rules | def list_topic_rules(topic=None, ruleDisabled=None,
region=None, key=None, keyid=None, profile=None):
'''
List all rules (for a given topic, if specified)
Returns list of rules
CLI Example:
.. code-block:: bash
salt myminion boto_iot.list_topic_rules
Example Return:
.. code-block:: yaml
rules:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if topic is not None:
kwargs['topic'] = topic
if ruleDisabled is not None:
kwargs['ruleDisabled'] = ruleDisabled
rules = []
for ret in __utils__['boto3.paged_call'](conn.list_topic_rules,
marker_flag='nextToken',
marker_arg='nextToken',
**kwargs):
rules.extend(ret['rules'])
if not bool(rules):
log.warning('No rules found')
return {'rules': rules}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | python | def list_topic_rules(topic=None, ruleDisabled=None,
region=None, key=None, keyid=None, profile=None):
'''
List all rules (for a given topic, if specified)
Returns list of rules
CLI Example:
.. code-block:: bash
salt myminion boto_iot.list_topic_rules
Example Return:
.. code-block:: yaml
rules:
- {...}
- {...}
'''
try:
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
kwargs = {}
if topic is not None:
kwargs['topic'] = topic
if ruleDisabled is not None:
kwargs['ruleDisabled'] = ruleDisabled
rules = []
for ret in __utils__['boto3.paged_call'](conn.list_topic_rules,
marker_flag='nextToken',
marker_arg='nextToken',
**kwargs):
rules.extend(ret['rules'])
if not bool(rules):
log.warning('No rules found')
return {'rules': rules}
except ClientError as e:
return {'error': __utils__['boto3.get_error'](e)} | [
"def",
"list_topic_rules",
"(",
"topic",
"=",
"None",
",",
"ruleDisabled",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
... | List all rules (for a given topic, if specified)
Returns list of rules
CLI Example:
.. code-block:: bash
salt myminion boto_iot.list_topic_rules
Example Return:
.. code-block:: yaml
rules:
- {...}
- {...} | [
"List",
"all",
"rules",
"(",
"for",
"a",
"given",
"topic",
"if",
"specified",
")"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_iot.py#L845-L884 | train |
saltstack/salt | salt/modules/netbsdservice.py | _get_svc | def _get_svc(rcd, service_status):
'''
Returns a unique service status
'''
ena = None
lines = __salt__['cmd.run']('{0} rcvar'.format(rcd)).splitlines()
for rcvar in lines:
if rcvar.startswith('$') and '={0}'.format(service_status) in rcvar:
ena = 'yes'
elif rcvar.startswith('#'):
svc = rcvar.split(' ', 1)[1]
else:
continue
if ena and svc:
return svc
return None | python | def _get_svc(rcd, service_status):
'''
Returns a unique service status
'''
ena = None
lines = __salt__['cmd.run']('{0} rcvar'.format(rcd)).splitlines()
for rcvar in lines:
if rcvar.startswith('$') and '={0}'.format(service_status) in rcvar:
ena = 'yes'
elif rcvar.startswith('#'):
svc = rcvar.split(' ', 1)[1]
else:
continue
if ena and svc:
return svc
return None | [
"def",
"_get_svc",
"(",
"rcd",
",",
"service_status",
")",
":",
"ena",
"=",
"None",
"lines",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'{0} rcvar'",
".",
"format",
"(",
"rcd",
")",
")",
".",
"splitlines",
"(",
")",
"for",
"rcvar",
"in",
"lines",
... | Returns a unique service status | [
"Returns",
"a",
"unique",
"service",
"status"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbsdservice.py#L146-L162 | train |
saltstack/salt | salt/modules/netbsdservice.py | _get_svc_list | def _get_svc_list(service_status):
'''
Returns all service statuses
'''
prefix = '/etc/rc.d/'
ret = set()
lines = glob.glob('{0}*'.format(prefix))
for line in lines:
svc = _get_svc(line, service_status)
if svc is not None:
ret.add(svc)
return sorted(ret) | python | def _get_svc_list(service_status):
'''
Returns all service statuses
'''
prefix = '/etc/rc.d/'
ret = set()
lines = glob.glob('{0}*'.format(prefix))
for line in lines:
svc = _get_svc(line, service_status)
if svc is not None:
ret.add(svc)
return sorted(ret) | [
"def",
"_get_svc_list",
"(",
"service_status",
")",
":",
"prefix",
"=",
"'/etc/rc.d/'",
"ret",
"=",
"set",
"(",
")",
"lines",
"=",
"glob",
".",
"glob",
"(",
"'{0}*'",
".",
"format",
"(",
"prefix",
")",
")",
"for",
"line",
"in",
"lines",
":",
"svc",
"... | Returns all service statuses | [
"Returns",
"all",
"service",
"statuses"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbsdservice.py#L165-L177 | train |
saltstack/salt | salt/modules/netbsdservice.py | _rcconf_status | def _rcconf_status(name, service_status):
'''
Modifies /etc/rc.conf so a service is started or not at boot time and
can be started via /etc/rc.d/<service>
'''
rcconf = '/etc/rc.conf'
rxname = '^{0}=.*'.format(name)
newstatus = '{0}={1}'.format(name, service_status)
ret = __salt__['cmd.retcode']('grep \'{0}\' {1}'.format(rxname, rcconf))
if ret == 0: # service found in rc.conf, modify its status
__salt__['file.replace'](rcconf, rxname, newstatus)
else:
ret = __salt__['file.append'](rcconf, newstatus)
return ret | python | def _rcconf_status(name, service_status):
'''
Modifies /etc/rc.conf so a service is started or not at boot time and
can be started via /etc/rc.d/<service>
'''
rcconf = '/etc/rc.conf'
rxname = '^{0}=.*'.format(name)
newstatus = '{0}={1}'.format(name, service_status)
ret = __salt__['cmd.retcode']('grep \'{0}\' {1}'.format(rxname, rcconf))
if ret == 0: # service found in rc.conf, modify its status
__salt__['file.replace'](rcconf, rxname, newstatus)
else:
ret = __salt__['file.append'](rcconf, newstatus)
return ret | [
"def",
"_rcconf_status",
"(",
"name",
",",
"service_status",
")",
":",
"rcconf",
"=",
"'/etc/rc.conf'",
"rxname",
"=",
"'^{0}=.*'",
".",
"format",
"(",
"name",
")",
"newstatus",
"=",
"'{0}={1}'",
".",
"format",
"(",
"name",
",",
"service_status",
")",
"ret",... | Modifies /etc/rc.conf so a service is started or not at boot time and
can be started via /etc/rc.d/<service> | [
"Modifies",
"/",
"etc",
"/",
"rc",
".",
"conf",
"so",
"a",
"service",
"is",
"started",
"or",
"not",
"at",
"boot",
"time",
"and",
"can",
"be",
"started",
"via",
"/",
"etc",
"/",
"rc",
".",
"d",
"/",
"<service",
">"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbsdservice.py#L248-L262 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | get_conn | def get_conn():
'''
Return a conn object for the passed VM data
'''
return ProfitBricksService(
username=config.get_cloud_config_value(
'username',
get_configured_provider(),
__opts__,
search_global=False
),
password=config.get_cloud_config_value(
'password',
get_configured_provider(),
__opts__,
search_global=False
)
) | python | def get_conn():
'''
Return a conn object for the passed VM data
'''
return ProfitBricksService(
username=config.get_cloud_config_value(
'username',
get_configured_provider(),
__opts__,
search_global=False
),
password=config.get_cloud_config_value(
'password',
get_configured_provider(),
__opts__,
search_global=False
)
) | [
"def",
"get_conn",
"(",
")",
":",
"return",
"ProfitBricksService",
"(",
"username",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'username'",
",",
"get_configured_provider",
"(",
")",
",",
"__opts__",
",",
"search_global",
"=",
"False",
")",
",",
"passwor... | Return a conn object for the passed VM data | [
"Return",
"a",
"conn",
"object",
"for",
"the",
"passed",
"VM",
"data"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L179-L196 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | avail_locations | def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-locations option'
)
ret = {}
conn = get_conn()
for item in conn.list_locations()['items']:
reg, loc = item['id'].split('/')
location = {'id': item['id']}
if reg not in ret:
ret[reg] = {}
ret[reg][loc] = location
return ret | python | def avail_locations(call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-locations option'
)
ret = {}
conn = get_conn()
for item in conn.list_locations()['items']:
reg, loc = item['id'].split('/')
location = {'id': item['id']}
if reg not in ret:
ret[reg] = {}
ret[reg][loc] = location
return ret | [
"def",
"avail_locations",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The avail_images function must be called with '",
"'-f or --function, or with the --list-locations option'",
")",
"ret",
"=",
"{",
"}"... | Return a dict of all available VM locations on the cloud provider with
relevant data | [
"Return",
"a",
"dict",
"of",
"all",
"available",
"VM",
"locations",
"on",
"the",
"cloud",
"provider",
"with",
"relevant",
"data"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L199-L221 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | avail_images | def avail_images(call=None):
'''
Return a list of the images that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
ret = {}
conn = get_conn()
for item in conn.list_images()['items']:
image = {'id': item['id']}
image.update(item['properties'])
ret[image['name']] = image
return ret | python | def avail_images(call=None):
'''
Return a list of the images that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
ret = {}
conn = get_conn()
for item in conn.list_images()['items']:
image = {'id': item['id']}
image.update(item['properties'])
ret[image['name']] = image
return ret | [
"def",
"avail_images",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The avail_images function must be called with '",
"'-f or --function, or with the --list-images option'",
")",
"ret",
"=",
"{",
"}",
"c... | Return a list of the images that are on the provider | [
"Return",
"a",
"list",
"of",
"the",
"images",
"that",
"are",
"on",
"the",
"provider"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L224-L242 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | list_images | def list_images(call=None, kwargs=None):
'''
List all the images with alias by location
CLI Example:
.. code-block:: bash
salt-cloud -f list_images my-profitbricks-config location=us/las
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_images function must be called with '
'-f or --function.'
)
if not version_compatible('4.0'):
raise SaltCloudNotFound(
"The 'image_alias' feature requires the profitbricks "
"SDK v4.0.0 or greater."
)
ret = {}
conn = get_conn()
if kwargs.get('location') is not None:
item = conn.get_location(kwargs.get('location'), 3)
ret[item['id']] = {'image_alias': item['properties']['imageAliases']}
return ret
for item in conn.list_locations(3)['items']:
ret[item['id']] = {'image_alias': item['properties']['imageAliases']}
return ret | python | def list_images(call=None, kwargs=None):
'''
List all the images with alias by location
CLI Example:
.. code-block:: bash
salt-cloud -f list_images my-profitbricks-config location=us/las
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_images function must be called with '
'-f or --function.'
)
if not version_compatible('4.0'):
raise SaltCloudNotFound(
"The 'image_alias' feature requires the profitbricks "
"SDK v4.0.0 or greater."
)
ret = {}
conn = get_conn()
if kwargs.get('location') is not None:
item = conn.get_location(kwargs.get('location'), 3)
ret[item['id']] = {'image_alias': item['properties']['imageAliases']}
return ret
for item in conn.list_locations(3)['items']:
ret[item['id']] = {'image_alias': item['properties']['imageAliases']}
return ret | [
"def",
"list_images",
"(",
"call",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_images function must be called with '",
"'-f or --function.'",
")",
"if",
"not",
"version_com... | List all the images with alias by location
CLI Example:
.. code-block:: bash
salt-cloud -f list_images my-profitbricks-config location=us/las | [
"List",
"all",
"the",
"images",
"with",
"alias",
"by",
"location"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L245-L278 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | get_size | def get_size(vm_):
'''
Return the VM's size object
'''
vm_size = config.get_cloud_config_value('size', vm_, __opts__)
sizes = avail_sizes()
if not vm_size:
return sizes['Small Instance']
for size in sizes:
combinations = (six.text_type(sizes[size]['id']), six.text_type(size))
if vm_size and six.text_type(vm_size) in combinations:
return sizes[size]
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
) | python | def get_size(vm_):
'''
Return the VM's size object
'''
vm_size = config.get_cloud_config_value('size', vm_, __opts__)
sizes = avail_sizes()
if not vm_size:
return sizes['Small Instance']
for size in sizes:
combinations = (six.text_type(sizes[size]['id']), six.text_type(size))
if vm_size and six.text_type(vm_size) in combinations:
return sizes[size]
raise SaltCloudNotFound(
'The specified size, \'{0}\', could not be found.'.format(vm_size)
) | [
"def",
"get_size",
"(",
"vm_",
")",
":",
"vm_size",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'size'",
",",
"vm_",
",",
"__opts__",
")",
"sizes",
"=",
"avail_sizes",
"(",
")",
"if",
"not",
"vm_size",
":",
"return",
"sizes",
"[",
"'Small Instance'... | Return the VM's size object | [
"Return",
"the",
"VM",
"s",
"size",
"object"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L340-L356 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | get_datacenter_id | def get_datacenter_id():
'''
Return datacenter ID from provider configuration
'''
datacenter_id = config.get_cloud_config_value(
'datacenter_id',
get_configured_provider(),
__opts__,
search_global=False
)
conn = get_conn()
try:
conn.get_datacenter(datacenter_id=datacenter_id)
except PBNotFoundError:
log.error('Failed to get datacenter: %s', datacenter_id)
raise
return datacenter_id | python | def get_datacenter_id():
'''
Return datacenter ID from provider configuration
'''
datacenter_id = config.get_cloud_config_value(
'datacenter_id',
get_configured_provider(),
__opts__,
search_global=False
)
conn = get_conn()
try:
conn.get_datacenter(datacenter_id=datacenter_id)
except PBNotFoundError:
log.error('Failed to get datacenter: %s', datacenter_id)
raise
return datacenter_id | [
"def",
"get_datacenter_id",
"(",
")",
":",
"datacenter_id",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'datacenter_id'",
",",
"get_configured_provider",
"(",
")",
",",
"__opts__",
",",
"search_global",
"=",
"False",
")",
"conn",
"=",
"get_conn",
"(",
")... | Return datacenter ID from provider configuration | [
"Return",
"datacenter",
"ID",
"from",
"provider",
"configuration"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L359-L378 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | list_loadbalancers | def list_loadbalancers(call=None):
'''
Return a list of the loadbalancers that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-loadbalancers option'
)
ret = {}
conn = get_conn()
datacenter = get_datacenter(conn)
for item in conn.list_loadbalancers(datacenter['id'])['items']:
lb = {'id': item['id']}
lb.update(item['properties'])
ret[lb['name']] = lb
return ret | python | def list_loadbalancers(call=None):
'''
Return a list of the loadbalancers that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-loadbalancers option'
)
ret = {}
conn = get_conn()
datacenter = get_datacenter(conn)
for item in conn.list_loadbalancers(datacenter['id'])['items']:
lb = {'id': item['id']}
lb.update(item['properties'])
ret[lb['name']] = lb
return ret | [
"def",
"list_loadbalancers",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The avail_images function must be called with '",
"'-f or --function, or with the --list-loadbalancers option'",
")",
"ret",
"=",
"{"... | Return a list of the loadbalancers that are on the provider | [
"Return",
"a",
"list",
"of",
"the",
"loadbalancers",
"that",
"are",
"on",
"the",
"provider"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L381-L400 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | create_loadbalancer | def create_loadbalancer(call=None, kwargs=None):
'''
Creates a loadbalancer within the datacenter from the provider config.
CLI Example:
.. code-block:: bash
salt-cloud -f create_loadbalancer profitbricks name=mylb
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_address function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
conn = get_conn()
datacenter_id = get_datacenter_id()
loadbalancer = LoadBalancer(name=kwargs.get('name'),
ip=kwargs.get('ip'),
dhcp=kwargs.get('dhcp'))
response = conn.create_loadbalancer(datacenter_id, loadbalancer)
_wait_for_completion(conn, response, 60, 'loadbalancer')
return response | python | def create_loadbalancer(call=None, kwargs=None):
'''
Creates a loadbalancer within the datacenter from the provider config.
CLI Example:
.. code-block:: bash
salt-cloud -f create_loadbalancer profitbricks name=mylb
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_address function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
conn = get_conn()
datacenter_id = get_datacenter_id()
loadbalancer = LoadBalancer(name=kwargs.get('name'),
ip=kwargs.get('ip'),
dhcp=kwargs.get('dhcp'))
response = conn.create_loadbalancer(datacenter_id, loadbalancer)
_wait_for_completion(conn, response, 60, 'loadbalancer')
return response | [
"def",
"create_loadbalancer",
"(",
"call",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The create_address function must be called with -f or --function.'",
")",
"if",
"kwargs",
"is",
... | Creates a loadbalancer within the datacenter from the provider config.
CLI Example:
.. code-block:: bash
salt-cloud -f create_loadbalancer profitbricks name=mylb | [
"Creates",
"a",
"loadbalancer",
"within",
"the",
"datacenter",
"from",
"the",
"provider",
"config",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L403-L430 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | get_datacenter | def get_datacenter(conn):
'''
Return the datacenter from the config provider datacenter ID
'''
datacenter_id = get_datacenter_id()
for item in conn.list_datacenters()['items']:
if item['id'] == datacenter_id:
return item
raise SaltCloudNotFound(
'The specified datacenter \'{0}\' could not be found.'.format(
datacenter_id
)
) | python | def get_datacenter(conn):
'''
Return the datacenter from the config provider datacenter ID
'''
datacenter_id = get_datacenter_id()
for item in conn.list_datacenters()['items']:
if item['id'] == datacenter_id:
return item
raise SaltCloudNotFound(
'The specified datacenter \'{0}\' could not be found.'.format(
datacenter_id
)
) | [
"def",
"get_datacenter",
"(",
"conn",
")",
":",
"datacenter_id",
"=",
"get_datacenter_id",
"(",
")",
"for",
"item",
"in",
"conn",
".",
"list_datacenters",
"(",
")",
"[",
"'items'",
"]",
":",
"if",
"item",
"[",
"'id'",
"]",
"==",
"datacenter_id",
":",
"re... | Return the datacenter from the config provider datacenter ID | [
"Return",
"the",
"datacenter",
"from",
"the",
"config",
"provider",
"datacenter",
"ID"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L433-L447 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | create_datacenter | def create_datacenter(call=None, kwargs=None):
'''
Creates a virtual datacenter based on supplied parameters.
CLI Example:
.. code-block:: bash
salt-cloud -f create_datacenter profitbricks name=mydatacenter
location=us/las description="my description"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_address function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if kwargs.get('name') is None:
raise SaltCloudExecutionFailure('The "name" parameter is required')
if kwargs.get('location') is None:
raise SaltCloudExecutionFailure('The "location" parameter is required')
conn = get_conn()
datacenter = Datacenter(name=kwargs['name'],
location=kwargs['location'],
description=kwargs.get('description'))
response = conn.create_datacenter(datacenter)
_wait_for_completion(conn, response, 60, 'create_datacenter')
return response | python | def create_datacenter(call=None, kwargs=None):
'''
Creates a virtual datacenter based on supplied parameters.
CLI Example:
.. code-block:: bash
salt-cloud -f create_datacenter profitbricks name=mydatacenter
location=us/las description="my description"
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_address function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if kwargs.get('name') is None:
raise SaltCloudExecutionFailure('The "name" parameter is required')
if kwargs.get('location') is None:
raise SaltCloudExecutionFailure('The "location" parameter is required')
conn = get_conn()
datacenter = Datacenter(name=kwargs['name'],
location=kwargs['location'],
description=kwargs.get('description'))
response = conn.create_datacenter(datacenter)
_wait_for_completion(conn, response, 60, 'create_datacenter')
return response | [
"def",
"create_datacenter",
"(",
"call",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The create_address function must be called with -f or --function.'",
")",
"if",
"kwargs",
"is",
... | Creates a virtual datacenter based on supplied parameters.
CLI Example:
.. code-block:: bash
salt-cloud -f create_datacenter profitbricks name=mydatacenter
location=us/las description="my description" | [
"Creates",
"a",
"virtual",
"datacenter",
"based",
"on",
"supplied",
"parameters",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L450-L483 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | list_datacenters | def list_datacenters(conn=None, call=None):
'''
List all the data centers
CLI Example:
.. code-block:: bash
salt-cloud -f list_datacenters my-profitbricks-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_datacenters function must be called with '
'-f or --function.'
)
datacenters = []
if not conn:
conn = get_conn()
for item in conn.list_datacenters()['items']:
datacenter = {'id': item['id']}
datacenter.update(item['properties'])
datacenters.append({item['properties']['name']: datacenter})
return {'Datacenters': datacenters} | python | def list_datacenters(conn=None, call=None):
'''
List all the data centers
CLI Example:
.. code-block:: bash
salt-cloud -f list_datacenters my-profitbricks-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_datacenters function must be called with '
'-f or --function.'
)
datacenters = []
if not conn:
conn = get_conn()
for item in conn.list_datacenters()['items']:
datacenter = {'id': item['id']}
datacenter.update(item['properties'])
datacenters.append({item['properties']['name']: datacenter})
return {'Datacenters': datacenters} | [
"def",
"list_datacenters",
"(",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_datacenters function must be called with '",
"'-f or --function.'",
")",
"datacenters",
"=",... | List all the data centers
CLI Example:
.. code-block:: bash
salt-cloud -f list_datacenters my-profitbricks-config | [
"List",
"all",
"the",
"data",
"centers"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L524-L550 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | list_nodes | def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
datacenter_id = get_datacenter_id()
try:
nodes = conn.list_servers(datacenter_id=datacenter_id)
except PBNotFoundError:
log.error('Failed to get nodes list '
'from datacenter: %s', datacenter_id)
raise
for item in nodes['items']:
node = {'id': item['id']}
node.update(item['properties'])
node['state'] = node.pop('vmState')
ret[node['name']] = node
return ret | python | def list_nodes(conn=None, call=None):
'''
Return a list of VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
datacenter_id = get_datacenter_id()
try:
nodes = conn.list_servers(datacenter_id=datacenter_id)
except PBNotFoundError:
log.error('Failed to get nodes list '
'from datacenter: %s', datacenter_id)
raise
for item in nodes['items']:
node = {'id': item['id']}
node.update(item['properties'])
node['state'] = node.pop('vmState')
ret[node['name']] = node
return ret | [
"def",
"list_nodes",
"(",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_nodes function must be called with -f or --function.'",
")",
"if",
"not",
"conn",
":",
"conn",
... | Return a list of VMs that are on the provider | [
"Return",
"a",
"list",
"of",
"VMs",
"that",
"are",
"on",
"the",
"provider"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L553-L581 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | list_nodes_full | def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
conn = get_conn() # pylint: disable=E0602
ret = {}
datacenter_id = get_datacenter_id()
nodes = conn.list_servers(datacenter_id=datacenter_id, depth=3)
for item in nodes['items']:
node = {'id': item['id']}
node.update(item['properties'])
node['state'] = node.pop('vmState')
node['public_ips'] = []
node['private_ips'] = []
if item['entities']['nics']['items'] > 0:
for nic in item['entities']['nics']['items']:
if nic['properties']['ips']:
pass
ip_address = nic['properties']['ips'][0]
if salt.utils.cloud.is_public_ip(ip_address):
node['public_ips'].append(ip_address)
else:
node['private_ips'].append(ip_address)
ret[node['name']] = node
__utils__['cloud.cache_node_list'](
ret,
__active_provider_name__.split(':')[0],
__opts__
)
return ret | python | def list_nodes_full(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with all fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or '
'--function.'
)
if not conn:
conn = get_conn() # pylint: disable=E0602
ret = {}
datacenter_id = get_datacenter_id()
nodes = conn.list_servers(datacenter_id=datacenter_id, depth=3)
for item in nodes['items']:
node = {'id': item['id']}
node.update(item['properties'])
node['state'] = node.pop('vmState')
node['public_ips'] = []
node['private_ips'] = []
if item['entities']['nics']['items'] > 0:
for nic in item['entities']['nics']['items']:
if nic['properties']['ips']:
pass
ip_address = nic['properties']['ips'][0]
if salt.utils.cloud.is_public_ip(ip_address):
node['public_ips'].append(ip_address)
else:
node['private_ips'].append(ip_address)
ret[node['name']] = node
__utils__['cloud.cache_node_list'](
ret,
__active_provider_name__.split(':')[0],
__opts__
)
return ret | [
"def",
"list_nodes_full",
"(",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_nodes_full function must be called with -f or '",
"'--function.'",
")",
"if",
"not",
"conn",
... | Return a list of the VMs that are on the provider, with all fields | [
"Return",
"a",
"list",
"of",
"the",
"VMs",
"that",
"are",
"on",
"the",
"provider",
"with",
"all",
"fields"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L584-L625 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | reserve_ipblock | def reserve_ipblock(call=None, kwargs=None):
'''
Reserve the IP Block
'''
if call == 'action':
raise SaltCloudSystemExit(
'The reserve_ipblock function must be called with -f or '
'--function.'
)
conn = get_conn()
if kwargs is None:
kwargs = {}
ret = {}
ret['ips'] = []
if kwargs.get('location') is None:
raise SaltCloudExecutionFailure('The "location" parameter is required')
location = kwargs.get('location')
size = 1
if kwargs.get('size') is not None:
size = kwargs.get('size')
block = conn.reserve_ipblock(IPBlock(size=size, location=location))
for item in block['properties']['ips']:
ret['ips'].append(item)
return ret | python | def reserve_ipblock(call=None, kwargs=None):
'''
Reserve the IP Block
'''
if call == 'action':
raise SaltCloudSystemExit(
'The reserve_ipblock function must be called with -f or '
'--function.'
)
conn = get_conn()
if kwargs is None:
kwargs = {}
ret = {}
ret['ips'] = []
if kwargs.get('location') is None:
raise SaltCloudExecutionFailure('The "location" parameter is required')
location = kwargs.get('location')
size = 1
if kwargs.get('size') is not None:
size = kwargs.get('size')
block = conn.reserve_ipblock(IPBlock(size=size, location=location))
for item in block['properties']['ips']:
ret['ips'].append(item)
return ret | [
"def",
"reserve_ipblock",
"(",
"call",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The reserve_ipblock function must be called with -f or '",
"'--function.'",
")",
"conn",
"=",
"get_c... | Reserve the IP Block | [
"Reserve",
"the",
"IP",
"Block"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L628-L658 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | get_node | def get_node(conn, name):
'''
Return a node for the named VM
'''
datacenter_id = get_datacenter_id()
for item in conn.list_servers(datacenter_id)['items']:
if item['properties']['name'] == name:
node = {'id': item['id']}
node.update(item['properties'])
return node | python | def get_node(conn, name):
'''
Return a node for the named VM
'''
datacenter_id = get_datacenter_id()
for item in conn.list_servers(datacenter_id)['items']:
if item['properties']['name'] == name:
node = {'id': item['id']}
node.update(item['properties'])
return node | [
"def",
"get_node",
"(",
"conn",
",",
"name",
")",
":",
"datacenter_id",
"=",
"get_datacenter_id",
"(",
")",
"for",
"item",
"in",
"conn",
".",
"list_servers",
"(",
"datacenter_id",
")",
"[",
"'items'",
"]",
":",
"if",
"item",
"[",
"'properties'",
"]",
"["... | Return a node for the named VM | [
"Return",
"a",
"node",
"for",
"the",
"named",
"VM"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L679-L689 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | _get_nics | def _get_nics(vm_):
'''
Create network interfaces on appropriate LANs as defined in cloud profile.
'''
nics = []
if 'public_lan' in vm_:
firewall_rules = []
# Set LAN to public if it already exists, otherwise create a new
# public LAN.
if 'public_firewall_rules' in vm_:
firewall_rules = _get_firewall_rules(vm_['public_firewall_rules'])
nic = NIC(lan=set_public_lan(int(vm_['public_lan'])),
name='public',
firewall_rules=firewall_rules)
if 'public_ips' in vm_:
nic.ips = _get_ip_addresses(vm_['public_ips'])
nics.append(nic)
if 'private_lan' in vm_:
firewall_rules = []
if 'private_firewall_rules' in vm_:
firewall_rules = _get_firewall_rules(vm_['private_firewall_rules'])
nic = NIC(lan=int(vm_['private_lan']),
name='private',
firewall_rules=firewall_rules)
if 'private_ips' in vm_:
nic.ips = _get_ip_addresses(vm_['private_ips'])
if 'nat' in vm_ and 'private_ips' not in vm_:
nic.nat = vm_['nat']
nics.append(nic)
return nics | python | def _get_nics(vm_):
'''
Create network interfaces on appropriate LANs as defined in cloud profile.
'''
nics = []
if 'public_lan' in vm_:
firewall_rules = []
# Set LAN to public if it already exists, otherwise create a new
# public LAN.
if 'public_firewall_rules' in vm_:
firewall_rules = _get_firewall_rules(vm_['public_firewall_rules'])
nic = NIC(lan=set_public_lan(int(vm_['public_lan'])),
name='public',
firewall_rules=firewall_rules)
if 'public_ips' in vm_:
nic.ips = _get_ip_addresses(vm_['public_ips'])
nics.append(nic)
if 'private_lan' in vm_:
firewall_rules = []
if 'private_firewall_rules' in vm_:
firewall_rules = _get_firewall_rules(vm_['private_firewall_rules'])
nic = NIC(lan=int(vm_['private_lan']),
name='private',
firewall_rules=firewall_rules)
if 'private_ips' in vm_:
nic.ips = _get_ip_addresses(vm_['private_ips'])
if 'nat' in vm_ and 'private_ips' not in vm_:
nic.nat = vm_['nat']
nics.append(nic)
return nics | [
"def",
"_get_nics",
"(",
"vm_",
")",
":",
"nics",
"=",
"[",
"]",
"if",
"'public_lan'",
"in",
"vm_",
":",
"firewall_rules",
"=",
"[",
"]",
"# Set LAN to public if it already exists, otherwise create a new",
"# public LAN.",
"if",
"'public_firewall_rules'",
"in",
"vm_",... | Create network interfaces on appropriate LANs as defined in cloud profile. | [
"Create",
"network",
"interfaces",
"on",
"appropriate",
"LANs",
"as",
"defined",
"in",
"cloud",
"profile",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L703-L733 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | set_public_lan | def set_public_lan(lan_id):
'''
Enables public Internet access for the specified public_lan. If no public
LAN is available, then a new public LAN is created.
'''
conn = get_conn()
datacenter_id = get_datacenter_id()
try:
lan = conn.get_lan(datacenter_id=datacenter_id, lan_id=lan_id)
if not lan['properties']['public']:
conn.update_lan(datacenter_id=datacenter_id,
lan_id=lan_id,
public=True)
return lan['id']
except Exception:
lan = conn.create_lan(datacenter_id,
LAN(public=True,
name='Public LAN'))
return lan['id'] | python | def set_public_lan(lan_id):
'''
Enables public Internet access for the specified public_lan. If no public
LAN is available, then a new public LAN is created.
'''
conn = get_conn()
datacenter_id = get_datacenter_id()
try:
lan = conn.get_lan(datacenter_id=datacenter_id, lan_id=lan_id)
if not lan['properties']['public']:
conn.update_lan(datacenter_id=datacenter_id,
lan_id=lan_id,
public=True)
return lan['id']
except Exception:
lan = conn.create_lan(datacenter_id,
LAN(public=True,
name='Public LAN'))
return lan['id'] | [
"def",
"set_public_lan",
"(",
"lan_id",
")",
":",
"conn",
"=",
"get_conn",
"(",
")",
"datacenter_id",
"=",
"get_datacenter_id",
"(",
")",
"try",
":",
"lan",
"=",
"conn",
".",
"get_lan",
"(",
"datacenter_id",
"=",
"datacenter_id",
",",
"lan_id",
"=",
"lan_i... | Enables public Internet access for the specified public_lan. If no public
LAN is available, then a new public LAN is created. | [
"Enables",
"public",
"Internet",
"access",
"for",
"the",
"specified",
"public_lan",
".",
"If",
"no",
"public",
"LAN",
"is",
"available",
"then",
"a",
"new",
"public",
"LAN",
"is",
"created",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L736-L755 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | get_public_keys | def get_public_keys(vm_):
'''
Retrieve list of SSH public keys.
'''
key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_public_key \'{0}\' does not exist'.format(
key_filename
)
)
ssh_keys = []
with salt.utils.files.fopen(key_filename) as rfh:
for key in rfh.readlines():
ssh_keys.append(salt.utils.stringutils.to_unicode(key))
return ssh_keys | python | def get_public_keys(vm_):
'''
Retrieve list of SSH public keys.
'''
key_filename = config.get_cloud_config_value(
'ssh_public_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_public_key \'{0}\' does not exist'.format(
key_filename
)
)
ssh_keys = []
with salt.utils.files.fopen(key_filename) as rfh:
for key in rfh.readlines():
ssh_keys.append(salt.utils.stringutils.to_unicode(key))
return ssh_keys | [
"def",
"get_public_keys",
"(",
"vm_",
")",
":",
"key_filename",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'ssh_public_key'",
",",
"vm_",
",",
"__opts__",
",",
"search_global",
"=",
"False",
",",
"default",
"=",
"None",
")",
"if",
"key_filename",
"is"... | Retrieve list of SSH public keys. | [
"Retrieve",
"list",
"of",
"SSH",
"public",
"keys",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L758-L778 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | get_key_filename | def get_key_filename(vm_):
'''
Check SSH private key file and return absolute path if exists.
'''
key_filename = config.get_cloud_config_value(
'ssh_private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_private_key \'{0}\' does not exist'.format(
key_filename
)
)
return key_filename | python | def get_key_filename(vm_):
'''
Check SSH private key file and return absolute path if exists.
'''
key_filename = config.get_cloud_config_value(
'ssh_private_key', vm_, __opts__, search_global=False, default=None
)
if key_filename is not None:
key_filename = os.path.expanduser(key_filename)
if not os.path.isfile(key_filename):
raise SaltCloudConfigError(
'The defined ssh_private_key \'{0}\' does not exist'.format(
key_filename
)
)
return key_filename | [
"def",
"get_key_filename",
"(",
"vm_",
")",
":",
"key_filename",
"=",
"config",
".",
"get_cloud_config_value",
"(",
"'ssh_private_key'",
",",
"vm_",
",",
"__opts__",
",",
"search_global",
"=",
"False",
",",
"default",
"=",
"None",
")",
"if",
"key_filename",
"i... | Check SSH private key file and return absolute path if exists. | [
"Check",
"SSH",
"private",
"key",
"file",
"and",
"return",
"absolute",
"path",
"if",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L781-L797 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | create | def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if (vm_['profile'] and
config.is_profile_configured(__opts__,
(__active_provider_name__ or
'profitbricks'),
vm_['profile']) is False):
return False
except AttributeError:
pass
if 'image_alias' in vm_ and not version_compatible('4.0'):
raise SaltCloudNotFound(
"The 'image_alias' parameter requires the profitbricks "
"SDK v4.0.0 or greater."
)
if 'image' not in vm_ and 'image_alias' not in vm_:
log.error('The image or image_alias parameter is required.')
signal_event(vm_, 'creating', 'starting create')
data = None
datacenter_id = get_datacenter_id()
conn = get_conn()
# Assemble list of network interfaces from the cloud profile config.
nics = _get_nics(vm_)
# Assemble list of volumes from the cloud profile config.
volumes = [_get_system_volume(vm_)]
if 'volumes' in vm_:
volumes.extend(_get_data_volumes(vm_))
# Assembla the composite server object.
server = _get_server(vm_, volumes, nics)
signal_event(vm_, 'requesting', 'requesting instance')
try:
data = conn.create_server(datacenter_id=datacenter_id, server=server)
log.info(
'Create server request ID: %s',
data['requestId'], exc_info_on_loglevel=logging.DEBUG
)
_wait_for_completion(conn, data, get_wait_timeout(vm_),
'create_server')
except PBError as exc:
log.error(
'Error creating %s on ProfitBricks\n\n'
'The following exception was thrown by the profitbricks library '
'when trying to run the initial deployment: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
except Exception as exc: # pylint: disable=W0703
log.error(
'Error creating %s \n\nError: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
vm_['server_id'] = data['id']
def __query_node_data(vm_, data):
'''
Query node data until node becomes available.
'''
running = False
try:
data = show_instance(vm_['name'], 'action')
if not data:
return False
log.debug(
'Loaded node data for %s:\nname: %s\nstate: %s',
vm_['name'], pprint.pformat(data['name']), data['state']
)
except Exception as err:
log.error(
'Failed to get nodes list: %s', err,
# Show the trackback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
# Trigger a failure in the wait for IP function
return False
running = data['state'] == 'RUNNING'
if not running:
# Still not running, trigger another iteration
return
if ssh_interface(vm_) == 'private_lan' and data['private_ips']:
vm_['ssh_host'] = data['private_ips'][0]
if ssh_interface(vm_) != 'private_lan' and data['public_ips']:
vm_['ssh_host'] = data['public_ips'][0]
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_, data),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc.message))
log.debug('VM is now running')
log.info('Created Cloud VM %s', vm_)
log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))
signal_event(vm_, 'created', 'created instance')
if 'ssh_host' in vm_:
vm_['key_filename'] = get_key_filename(vm_)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
return ret
else:
raise SaltCloudSystemExit('A valid IP address was not found.') | python | def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if (vm_['profile'] and
config.is_profile_configured(__opts__,
(__active_provider_name__ or
'profitbricks'),
vm_['profile']) is False):
return False
except AttributeError:
pass
if 'image_alias' in vm_ and not version_compatible('4.0'):
raise SaltCloudNotFound(
"The 'image_alias' parameter requires the profitbricks "
"SDK v4.0.0 or greater."
)
if 'image' not in vm_ and 'image_alias' not in vm_:
log.error('The image or image_alias parameter is required.')
signal_event(vm_, 'creating', 'starting create')
data = None
datacenter_id = get_datacenter_id()
conn = get_conn()
# Assemble list of network interfaces from the cloud profile config.
nics = _get_nics(vm_)
# Assemble list of volumes from the cloud profile config.
volumes = [_get_system_volume(vm_)]
if 'volumes' in vm_:
volumes.extend(_get_data_volumes(vm_))
# Assembla the composite server object.
server = _get_server(vm_, volumes, nics)
signal_event(vm_, 'requesting', 'requesting instance')
try:
data = conn.create_server(datacenter_id=datacenter_id, server=server)
log.info(
'Create server request ID: %s',
data['requestId'], exc_info_on_loglevel=logging.DEBUG
)
_wait_for_completion(conn, data, get_wait_timeout(vm_),
'create_server')
except PBError as exc:
log.error(
'Error creating %s on ProfitBricks\n\n'
'The following exception was thrown by the profitbricks library '
'when trying to run the initial deployment: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
except Exception as exc: # pylint: disable=W0703
log.error(
'Error creating %s \n\nError: \n%s',
vm_['name'], exc, exc_info_on_loglevel=logging.DEBUG
)
return False
vm_['server_id'] = data['id']
def __query_node_data(vm_, data):
'''
Query node data until node becomes available.
'''
running = False
try:
data = show_instance(vm_['name'], 'action')
if not data:
return False
log.debug(
'Loaded node data for %s:\nname: %s\nstate: %s',
vm_['name'], pprint.pformat(data['name']), data['state']
)
except Exception as err:
log.error(
'Failed to get nodes list: %s', err,
# Show the trackback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
# Trigger a failure in the wait for IP function
return False
running = data['state'] == 'RUNNING'
if not running:
# Still not running, trigger another iteration
return
if ssh_interface(vm_) == 'private_lan' and data['private_ips']:
vm_['ssh_host'] = data['private_ips'][0]
if ssh_interface(vm_) != 'private_lan' and data['public_ips']:
vm_['ssh_host'] = data['public_ips'][0]
return data
try:
data = salt.utils.cloud.wait_for_ip(
__query_node_data,
update_args=(vm_, data),
timeout=config.get_cloud_config_value(
'wait_for_ip_timeout', vm_, __opts__, default=10 * 60),
interval=config.get_cloud_config_value(
'wait_for_ip_interval', vm_, __opts__, default=10),
)
except (SaltCloudExecutionTimeout, SaltCloudExecutionFailure) as exc:
try:
# It might be already up, let's destroy it!
destroy(vm_['name'])
except SaltCloudSystemExit:
pass
finally:
raise SaltCloudSystemExit(six.text_type(exc.message))
log.debug('VM is now running')
log.info('Created Cloud VM %s', vm_)
log.debug('%s VM creation details:\n%s', vm_, pprint.pformat(data))
signal_event(vm_, 'created', 'created instance')
if 'ssh_host' in vm_:
vm_['key_filename'] = get_key_filename(vm_)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
ret.update(data)
return ret
else:
raise SaltCloudSystemExit('A valid IP address was not found.') | [
"def",
"create",
"(",
"vm_",
")",
":",
"try",
":",
"# Check for required profile parameters before sending any API calls.",
"if",
"(",
"vm_",
"[",
"'profile'",
"]",
"and",
"config",
".",
"is_profile_configured",
"(",
"__opts__",
",",
"(",
"__active_provider_name__",
"... | Create a single VM from a data dict | [
"Create",
"a",
"single",
"VM",
"from",
"a",
"data",
"dict"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L817-L951 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | destroy | def destroy(name, call=None):
'''
destroy a machine by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
datacenter_id = get_datacenter_id()
conn = get_conn()
node = get_node(conn, name)
attached_volumes = None
delete_volumes = config.get_cloud_config_value(
'delete_volumes',
get_configured_provider(),
__opts__,
search_global=False
)
# Get volumes before the server is deleted
attached_volumes = conn.get_attached_volumes(
datacenter_id=datacenter_id,
server_id=node['id']
)
conn.delete_server(datacenter_id=datacenter_id, server_id=node['id'])
# The server is deleted and now is safe to delete the volumes
if delete_volumes:
for vol in attached_volumes['items']:
log.debug('Deleting volume %s', vol['id'])
conn.delete_volume(
datacenter_id=datacenter_id,
volume_id=vol['id']
)
log.debug('Deleted volume %s', vol['id'])
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](
name,
__active_provider_name__.split(':')[0],
__opts__
)
return True | python | def destroy(name, call=None):
'''
destroy a machine by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
__utils__['cloud.fire_event'](
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
datacenter_id = get_datacenter_id()
conn = get_conn()
node = get_node(conn, name)
attached_volumes = None
delete_volumes = config.get_cloud_config_value(
'delete_volumes',
get_configured_provider(),
__opts__,
search_global=False
)
# Get volumes before the server is deleted
attached_volumes = conn.get_attached_volumes(
datacenter_id=datacenter_id,
server_id=node['id']
)
conn.delete_server(datacenter_id=datacenter_id, server_id=node['id'])
# The server is deleted and now is safe to delete the volumes
if delete_volumes:
for vol in attached_volumes['items']:
log.debug('Deleting volume %s', vol['id'])
conn.delete_volume(
datacenter_id=datacenter_id,
volume_id=vol['id']
)
log.debug('Deleted volume %s', vol['id'])
__utils__['cloud.fire_event'](
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
args={'name': name},
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](
name,
__active_provider_name__.split(':')[0],
__opts__
)
return True | [
"def",
"destroy",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The destroy action must be called with -d, --destroy, '",
"'-a or --action.'",
")",
"__utils__",
"[",
"'cloud.fire_event'",
... | destroy a machine by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: array of booleans , true if successfully stopped and true if
successfully removed
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name | [
"destroy",
"a",
"machine",
"by",
"name"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L954-L1030 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | reboot | def reboot(name, call=None):
'''
reboot a machine by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
datacenter_id = get_datacenter_id()
conn = get_conn()
node = get_node(conn, name)
conn.reboot_server(datacenter_id=datacenter_id, server_id=node['id'])
return True | python | def reboot(name, call=None):
'''
reboot a machine by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name
'''
datacenter_id = get_datacenter_id()
conn = get_conn()
node = get_node(conn, name)
conn.reboot_server(datacenter_id=datacenter_id, server_id=node['id'])
return True | [
"def",
"reboot",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"datacenter_id",
"=",
"get_datacenter_id",
"(",
")",
"conn",
"=",
"get_conn",
"(",
")",
"node",
"=",
"get_node",
"(",
"conn",
",",
"name",
")",
"conn",
".",
"reboot_server",
"(",
"datace... | reboot a machine by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a reboot vm_name | [
"reboot",
"a",
"machine",
"by",
"name",
":",
"param",
"name",
":",
"name",
"given",
"to",
"the",
"machine",
":",
"param",
"call",
":",
"call",
"value",
"in",
"this",
"case",
"is",
"action",
":",
"return",
":",
"true",
"if",
"successful"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L1033-L1052 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | stop | def stop(name, call=None):
'''
stop a machine by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
datacenter_id = get_datacenter_id()
conn = get_conn()
node = get_node(conn, name)
conn.stop_server(datacenter_id=datacenter_id, server_id=node['id'])
return True | python | def stop(name, call=None):
'''
stop a machine by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name
'''
datacenter_id = get_datacenter_id()
conn = get_conn()
node = get_node(conn, name)
conn.stop_server(datacenter_id=datacenter_id, server_id=node['id'])
return True | [
"def",
"stop",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"datacenter_id",
"=",
"get_datacenter_id",
"(",
")",
"conn",
"=",
"get_conn",
"(",
")",
"node",
"=",
"get_node",
"(",
"conn",
",",
"name",
")",
"conn",
".",
"stop_server",
"(",
"datacenter... | stop a machine by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a stop vm_name | [
"stop",
"a",
"machine",
"by",
"name",
":",
"param",
"name",
":",
"name",
"given",
"to",
"the",
"machine",
":",
"param",
"call",
":",
"call",
"value",
"in",
"this",
"case",
"is",
"action",
":",
"return",
":",
"true",
"if",
"successful"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L1055-L1074 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | start | def start(name, call=None):
'''
start a machine by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name
'''
datacenter_id = get_datacenter_id()
conn = get_conn()
node = get_node(conn, name)
conn.start_server(datacenter_id=datacenter_id, server_id=node['id'])
return True | python | def start(name, call=None):
'''
start a machine by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name
'''
datacenter_id = get_datacenter_id()
conn = get_conn()
node = get_node(conn, name)
conn.start_server(datacenter_id=datacenter_id, server_id=node['id'])
return True | [
"def",
"start",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"datacenter_id",
"=",
"get_datacenter_id",
"(",
")",
"conn",
"=",
"get_conn",
"(",
")",
"node",
"=",
"get_node",
"(",
"conn",
",",
"name",
")",
"conn",
".",
"start_server",
"(",
"datacent... | start a machine by name
:param name: name given to the machine
:param call: call value in this case is 'action'
:return: true if successful
CLI Example:
.. code-block:: bash
salt-cloud -a start vm_name | [
"start",
"a",
"machine",
"by",
"name",
":",
"param",
"name",
":",
"name",
"given",
"to",
"the",
"machine",
":",
"param",
"call",
":",
"call",
"value",
"in",
"this",
"case",
"is",
"action",
":",
"return",
":",
"true",
"if",
"successful"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L1077-L1097 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | _override_size | def _override_size(vm_):
'''
Apply any extra component overrides to VM from the cloud profile.
'''
vm_size = get_size(vm_)
if 'cores' in vm_:
vm_size['cores'] = vm_['cores']
if 'ram' in vm_:
vm_size['ram'] = vm_['ram']
return vm_size | python | def _override_size(vm_):
'''
Apply any extra component overrides to VM from the cloud profile.
'''
vm_size = get_size(vm_)
if 'cores' in vm_:
vm_size['cores'] = vm_['cores']
if 'ram' in vm_:
vm_size['ram'] = vm_['ram']
return vm_size | [
"def",
"_override_size",
"(",
"vm_",
")",
":",
"vm_size",
"=",
"get_size",
"(",
"vm_",
")",
"if",
"'cores'",
"in",
"vm_",
":",
"vm_size",
"[",
"'cores'",
"]",
"=",
"vm_",
"[",
"'cores'",
"]",
"if",
"'ram'",
"in",
"vm_",
":",
"vm_size",
"[",
"'ram'",
... | Apply any extra component overrides to VM from the cloud profile. | [
"Apply",
"any",
"extra",
"component",
"overrides",
"to",
"VM",
"from",
"the",
"cloud",
"profile",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L1100-L1112 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | _get_server | def _get_server(vm_, volumes, nics):
'''
Construct server instance from cloud profile config
'''
# Apply component overrides to the size from the cloud profile config
vm_size = _override_size(vm_)
# Set the server availability zone from the cloud profile config
availability_zone = config.get_cloud_config_value(
'availability_zone', vm_, __opts__, default=None,
search_global=False
)
# Assign CPU family from the cloud profile config
cpu_family = config.get_cloud_config_value(
'cpu_family', vm_, __opts__, default=None,
search_global=False
)
# Contruct server object
return Server(
name=vm_['name'],
ram=vm_size['ram'],
availability_zone=availability_zone,
cores=vm_size['cores'],
cpu_family=cpu_family,
create_volumes=volumes,
nics=nics
) | python | def _get_server(vm_, volumes, nics):
'''
Construct server instance from cloud profile config
'''
# Apply component overrides to the size from the cloud profile config
vm_size = _override_size(vm_)
# Set the server availability zone from the cloud profile config
availability_zone = config.get_cloud_config_value(
'availability_zone', vm_, __opts__, default=None,
search_global=False
)
# Assign CPU family from the cloud profile config
cpu_family = config.get_cloud_config_value(
'cpu_family', vm_, __opts__, default=None,
search_global=False
)
# Contruct server object
return Server(
name=vm_['name'],
ram=vm_size['ram'],
availability_zone=availability_zone,
cores=vm_size['cores'],
cpu_family=cpu_family,
create_volumes=volumes,
nics=nics
) | [
"def",
"_get_server",
"(",
"vm_",
",",
"volumes",
",",
"nics",
")",
":",
"# Apply component overrides to the size from the cloud profile config",
"vm_size",
"=",
"_override_size",
"(",
"vm_",
")",
"# Set the server availability zone from the cloud profile config",
"availability_z... | Construct server instance from cloud profile config | [
"Construct",
"server",
"instance",
"from",
"cloud",
"profile",
"config"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L1115-L1143 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | _get_system_volume | def _get_system_volume(vm_):
'''
Construct VM system volume list from cloud profile config
'''
# Override system volume size if 'disk_size' is defined in cloud profile
disk_size = get_size(vm_)['disk']
if 'disk_size' in vm_:
disk_size = vm_['disk_size']
# Construct the system volume
volume = Volume(
name='{0} Storage'.format(vm_['name']),
size=disk_size,
disk_type=get_disk_type(vm_)
)
if 'image_password' in vm_:
image_password = vm_['image_password']
volume.image_password = image_password
# Retrieve list of SSH public keys
ssh_keys = get_public_keys(vm_)
volume.ssh_keys = ssh_keys
if 'image_alias' in vm_.keys():
volume.image_alias = vm_['image_alias']
else:
volume.image = get_image(vm_)['id']
# Set volume availability zone if defined in the cloud profile
if 'disk_availability_zone' in vm_:
volume.availability_zone = vm_['disk_availability_zone']
return volume | python | def _get_system_volume(vm_):
'''
Construct VM system volume list from cloud profile config
'''
# Override system volume size if 'disk_size' is defined in cloud profile
disk_size = get_size(vm_)['disk']
if 'disk_size' in vm_:
disk_size = vm_['disk_size']
# Construct the system volume
volume = Volume(
name='{0} Storage'.format(vm_['name']),
size=disk_size,
disk_type=get_disk_type(vm_)
)
if 'image_password' in vm_:
image_password = vm_['image_password']
volume.image_password = image_password
# Retrieve list of SSH public keys
ssh_keys = get_public_keys(vm_)
volume.ssh_keys = ssh_keys
if 'image_alias' in vm_.keys():
volume.image_alias = vm_['image_alias']
else:
volume.image = get_image(vm_)['id']
# Set volume availability zone if defined in the cloud profile
if 'disk_availability_zone' in vm_:
volume.availability_zone = vm_['disk_availability_zone']
return volume | [
"def",
"_get_system_volume",
"(",
"vm_",
")",
":",
"# Override system volume size if 'disk_size' is defined in cloud profile",
"disk_size",
"=",
"get_size",
"(",
"vm_",
")",
"[",
"'disk'",
"]",
"if",
"'disk_size'",
"in",
"vm_",
":",
"disk_size",
"=",
"vm_",
"[",
"'d... | Construct VM system volume list from cloud profile config | [
"Construct",
"VM",
"system",
"volume",
"list",
"from",
"cloud",
"profile",
"config"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L1146-L1179 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | _get_data_volumes | def _get_data_volumes(vm_):
'''
Construct a list of optional data volumes from the cloud profile
'''
ret = []
volumes = vm_['volumes']
for key, value in six.iteritems(volumes):
# Verify the required 'disk_size' property is present in the cloud
# profile config
if 'disk_size' not in volumes[key].keys():
raise SaltCloudConfigError(
'The volume \'{0}\' is missing \'disk_size\''.format(key)
)
# Use 'HDD' if no 'disk_type' property is present in cloud profile
if 'disk_type' not in volumes[key].keys():
volumes[key]['disk_type'] = 'HDD'
# Construct volume object and assign to a list.
volume = Volume(
name=key,
size=volumes[key]['disk_size'],
disk_type=volumes[key]['disk_type'],
licence_type='OTHER'
)
# Set volume availability zone if defined in the cloud profile
if 'disk_availability_zone' in volumes[key].keys():
volume.availability_zone = volumes[key]['disk_availability_zone']
ret.append(volume)
return ret | python | def _get_data_volumes(vm_):
'''
Construct a list of optional data volumes from the cloud profile
'''
ret = []
volumes = vm_['volumes']
for key, value in six.iteritems(volumes):
# Verify the required 'disk_size' property is present in the cloud
# profile config
if 'disk_size' not in volumes[key].keys():
raise SaltCloudConfigError(
'The volume \'{0}\' is missing \'disk_size\''.format(key)
)
# Use 'HDD' if no 'disk_type' property is present in cloud profile
if 'disk_type' not in volumes[key].keys():
volumes[key]['disk_type'] = 'HDD'
# Construct volume object and assign to a list.
volume = Volume(
name=key,
size=volumes[key]['disk_size'],
disk_type=volumes[key]['disk_type'],
licence_type='OTHER'
)
# Set volume availability zone if defined in the cloud profile
if 'disk_availability_zone' in volumes[key].keys():
volume.availability_zone = volumes[key]['disk_availability_zone']
ret.append(volume)
return ret | [
"def",
"_get_data_volumes",
"(",
"vm_",
")",
":",
"ret",
"=",
"[",
"]",
"volumes",
"=",
"vm_",
"[",
"'volumes'",
"]",
"for",
"key",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"volumes",
")",
":",
"# Verify the required 'disk_size' property is present in... | Construct a list of optional data volumes from the cloud profile | [
"Construct",
"a",
"list",
"of",
"optional",
"data",
"volumes",
"from",
"the",
"cloud",
"profile"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L1182-L1213 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | _get_firewall_rules | def _get_firewall_rules(firewall_rules):
'''
Construct a list of optional firewall rules from the cloud profile.
'''
ret = []
for key, value in six.iteritems(firewall_rules):
# Verify the required 'protocol' property is present in the cloud
# profile config
if 'protocol' not in firewall_rules[key].keys():
raise SaltCloudConfigError(
'The firewall rule \'{0}\' is missing \'protocol\''.format(key)
)
ret.append(FirewallRule(
name=key,
protocol=firewall_rules[key].get('protocol', None),
source_mac=firewall_rules[key].get('source_mac', None),
source_ip=firewall_rules[key].get('source_ip', None),
target_ip=firewall_rules[key].get('target_ip', None),
port_range_start=firewall_rules[key].get('port_range_start', None),
port_range_end=firewall_rules[key].get('port_range_end', None),
icmp_type=firewall_rules[key].get('icmp_type', None),
icmp_code=firewall_rules[key].get('icmp_code', None)
))
return ret | python | def _get_firewall_rules(firewall_rules):
'''
Construct a list of optional firewall rules from the cloud profile.
'''
ret = []
for key, value in six.iteritems(firewall_rules):
# Verify the required 'protocol' property is present in the cloud
# profile config
if 'protocol' not in firewall_rules[key].keys():
raise SaltCloudConfigError(
'The firewall rule \'{0}\' is missing \'protocol\''.format(key)
)
ret.append(FirewallRule(
name=key,
protocol=firewall_rules[key].get('protocol', None),
source_mac=firewall_rules[key].get('source_mac', None),
source_ip=firewall_rules[key].get('source_ip', None),
target_ip=firewall_rules[key].get('target_ip', None),
port_range_start=firewall_rules[key].get('port_range_start', None),
port_range_end=firewall_rules[key].get('port_range_end', None),
icmp_type=firewall_rules[key].get('icmp_type', None),
icmp_code=firewall_rules[key].get('icmp_code', None)
))
return ret | [
"def",
"_get_firewall_rules",
"(",
"firewall_rules",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"six",
".",
"iteritems",
"(",
"firewall_rules",
")",
":",
"# Verify the required 'protocol' property is present in the cloud",
"# profile config",
"i... | Construct a list of optional firewall rules from the cloud profile. | [
"Construct",
"a",
"list",
"of",
"optional",
"firewall",
"rules",
"from",
"the",
"cloud",
"profile",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L1227-L1251 | train |
saltstack/salt | salt/cloud/clouds/profitbricks.py | _wait_for_completion | def _wait_for_completion(conn, promise, wait_timeout, msg):
'''
Poll request status until resource is provisioned.
'''
if not promise:
return
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(5)
operation_result = conn.get_request(
request_id=promise['requestId'],
status=True)
if operation_result['metadata']['status'] == "DONE":
return
elif operation_result['metadata']['status'] == "FAILED":
raise Exception(
"Request: {0}, requestId: {1} failed to complete:\n{2}".format(
msg, six.text_type(promise['requestId']),
operation_result['metadata']['message']
)
)
raise Exception(
'Timed out waiting for asynchronous operation {0} "{1}" to complete.'.format(
msg, six.text_type(promise['requestId'])
)
) | python | def _wait_for_completion(conn, promise, wait_timeout, msg):
'''
Poll request status until resource is provisioned.
'''
if not promise:
return
wait_timeout = time.time() + wait_timeout
while wait_timeout > time.time():
time.sleep(5)
operation_result = conn.get_request(
request_id=promise['requestId'],
status=True)
if operation_result['metadata']['status'] == "DONE":
return
elif operation_result['metadata']['status'] == "FAILED":
raise Exception(
"Request: {0}, requestId: {1} failed to complete:\n{2}".format(
msg, six.text_type(promise['requestId']),
operation_result['metadata']['message']
)
)
raise Exception(
'Timed out waiting for asynchronous operation {0} "{1}" to complete.'.format(
msg, six.text_type(promise['requestId'])
)
) | [
"def",
"_wait_for_completion",
"(",
"conn",
",",
"promise",
",",
"wait_timeout",
",",
"msg",
")",
":",
"if",
"not",
"promise",
":",
"return",
"wait_timeout",
"=",
"time",
".",
"time",
"(",
")",
"+",
"wait_timeout",
"while",
"wait_timeout",
">",
"time",
"."... | Poll request status until resource is provisioned. | [
"Poll",
"request",
"status",
"until",
"resource",
"is",
"provisioned",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/profitbricks.py#L1254-L1281 | train |
saltstack/salt | salt/modules/flatpak.py | is_installed | def is_installed(name):
'''
Determine if a package or runtime is installed.
Args:
name (str): The name of the package or the runtime.
Returns:
bool: True if the specified package or runtime is installed.
CLI Example:
.. code-block:: bash
salt '*' flatpak.is_installed org.gimp.GIMP
'''
out = __salt__['cmd.run_all'](FLATPAK_BINARY_NAME + ' info ' + name)
if out['retcode'] and out['stderr']:
return False
else:
return True | python | def is_installed(name):
'''
Determine if a package or runtime is installed.
Args:
name (str): The name of the package or the runtime.
Returns:
bool: True if the specified package or runtime is installed.
CLI Example:
.. code-block:: bash
salt '*' flatpak.is_installed org.gimp.GIMP
'''
out = __salt__['cmd.run_all'](FLATPAK_BINARY_NAME + ' info ' + name)
if out['retcode'] and out['stderr']:
return False
else:
return True | [
"def",
"is_installed",
"(",
"name",
")",
":",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"FLATPAK_BINARY_NAME",
"+",
"' info '",
"+",
"name",
")",
"if",
"out",
"[",
"'retcode'",
"]",
"and",
"out",
"[",
"'stderr'",
"]",
":",
"return",
"False"... | Determine if a package or runtime is installed.
Args:
name (str): The name of the package or the runtime.
Returns:
bool: True if the specified package or runtime is installed.
CLI Example:
.. code-block:: bash
salt '*' flatpak.is_installed org.gimp.GIMP | [
"Determine",
"if",
"a",
"package",
"or",
"runtime",
"is",
"installed",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/flatpak.py#L58-L79 | train |
saltstack/salt | salt/modules/flatpak.py | uninstall | def uninstall(pkg):
'''
Uninstall the specified package.
Args:
pkg (str): The package name.
Returns:
dict: The ``result`` and ``output``.
CLI Example:
.. code-block:: bash
salt '*' flatpak.uninstall org.gimp.GIMP
'''
ret = {'result': None, 'output': ''}
out = __salt__['cmd.run_all'](FLATPAK_BINARY_NAME + ' uninstall ' + pkg)
if out['retcode'] and out['stderr']:
ret['stderr'] = out['stderr'].strip()
ret['result'] = False
else:
ret['stdout'] = out['stdout'].strip()
ret['result'] = True
return ret | python | def uninstall(pkg):
'''
Uninstall the specified package.
Args:
pkg (str): The package name.
Returns:
dict: The ``result`` and ``output``.
CLI Example:
.. code-block:: bash
salt '*' flatpak.uninstall org.gimp.GIMP
'''
ret = {'result': None, 'output': ''}
out = __salt__['cmd.run_all'](FLATPAK_BINARY_NAME + ' uninstall ' + pkg)
if out['retcode'] and out['stderr']:
ret['stderr'] = out['stderr'].strip()
ret['result'] = False
else:
ret['stdout'] = out['stdout'].strip()
ret['result'] = True
return ret | [
"def",
"uninstall",
"(",
"pkg",
")",
":",
"ret",
"=",
"{",
"'result'",
":",
"None",
",",
"'output'",
":",
"''",
"}",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"FLATPAK_BINARY_NAME",
"+",
"' uninstall '",
"+",
"pkg",
")",
"if",
"out",
"[",... | Uninstall the specified package.
Args:
pkg (str): The package name.
Returns:
dict: The ``result`` and ``output``.
CLI Example:
.. code-block:: bash
salt '*' flatpak.uninstall org.gimp.GIMP | [
"Uninstall",
"the",
"specified",
"package",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/flatpak.py#L82-L109 | train |
saltstack/salt | salt/modules/flatpak.py | add_remote | def add_remote(name, location):
'''
Adds a new location to install flatpak packages from.
Args:
name (str): The repository's name.
location (str): The location of the repository.
Returns:
dict: The ``result`` and ``output``.
CLI Example:
.. code-block:: bash
salt '*' flatpak.add_remote flathub https://flathub.org/repo/flathub.flatpakrepo
'''
ret = {'result': None, 'output': ''}
out = __salt__['cmd.run_all'](FLATPAK_BINARY_NAME + ' remote-add ' + name + ' ' + location)
if out['retcode'] and out['stderr']:
ret['stderr'] = out['stderr'].strip()
ret['result'] = False
else:
ret['stdout'] = out['stdout'].strip()
ret['result'] = True
return ret | python | def add_remote(name, location):
'''
Adds a new location to install flatpak packages from.
Args:
name (str): The repository's name.
location (str): The location of the repository.
Returns:
dict: The ``result`` and ``output``.
CLI Example:
.. code-block:: bash
salt '*' flatpak.add_remote flathub https://flathub.org/repo/flathub.flatpakrepo
'''
ret = {'result': None, 'output': ''}
out = __salt__['cmd.run_all'](FLATPAK_BINARY_NAME + ' remote-add ' + name + ' ' + location)
if out['retcode'] and out['stderr']:
ret['stderr'] = out['stderr'].strip()
ret['result'] = False
else:
ret['stdout'] = out['stdout'].strip()
ret['result'] = True
return ret | [
"def",
"add_remote",
"(",
"name",
",",
"location",
")",
":",
"ret",
"=",
"{",
"'result'",
":",
"None",
",",
"'output'",
":",
"''",
"}",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"FLATPAK_BINARY_NAME",
"+",
"' remote-add '",
"+",
"name",
"+"... | Adds a new location to install flatpak packages from.
Args:
name (str): The repository's name.
location (str): The location of the repository.
Returns:
dict: The ``result`` and ``output``.
CLI Example:
.. code-block:: bash
salt '*' flatpak.add_remote flathub https://flathub.org/repo/flathub.flatpakrepo | [
"Adds",
"a",
"new",
"location",
"to",
"install",
"flatpak",
"packages",
"from",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/flatpak.py#L112-L139 | train |
saltstack/salt | salt/modules/flatpak.py | is_remote_added | def is_remote_added(remote):
'''
Determines if a remote exists.
Args:
remote (str): The remote's name.
Returns:
bool: True if the remote has already been added.
CLI Example:
.. code-block:: bash
salt '*' flatpak.is_remote_added flathub
'''
out = __salt__['cmd.run_all'](FLATPAK_BINARY_NAME + ' remotes')
lines = out.splitlines()
for item in lines:
i = re.split(r'\t+', item.rstrip('\t'))
if i[0] == remote:
return True
return False | python | def is_remote_added(remote):
'''
Determines if a remote exists.
Args:
remote (str): The remote's name.
Returns:
bool: True if the remote has already been added.
CLI Example:
.. code-block:: bash
salt '*' flatpak.is_remote_added flathub
'''
out = __salt__['cmd.run_all'](FLATPAK_BINARY_NAME + ' remotes')
lines = out.splitlines()
for item in lines:
i = re.split(r'\t+', item.rstrip('\t'))
if i[0] == remote:
return True
return False | [
"def",
"is_remote_added",
"(",
"remote",
")",
":",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"FLATPAK_BINARY_NAME",
"+",
"' remotes'",
")",
"lines",
"=",
"out",
".",
"splitlines",
"(",
")",
"for",
"item",
"in",
"lines",
":",
"i",
"=",
"re",... | Determines if a remote exists.
Args:
remote (str): The remote's name.
Returns:
bool: True if the remote has already been added.
CLI Example:
.. code-block:: bash
salt '*' flatpak.is_remote_added flathub | [
"Determines",
"if",
"a",
"remote",
"exists",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/flatpak.py#L142-L165 | train |
saltstack/salt | salt/utils/compat.py | pack_dunder | def pack_dunder(name):
'''
Compatibility helper function to make __utils__ available on demand.
'''
# TODO: Deprecate starting with Beryllium
mod = sys.modules[name]
if not hasattr(mod, '__utils__'):
setattr(mod, '__utils__', salt.loader.utils(mod.__opts__)) | python | def pack_dunder(name):
'''
Compatibility helper function to make __utils__ available on demand.
'''
# TODO: Deprecate starting with Beryllium
mod = sys.modules[name]
if not hasattr(mod, '__utils__'):
setattr(mod, '__utils__', salt.loader.utils(mod.__opts__)) | [
"def",
"pack_dunder",
"(",
"name",
")",
":",
"# TODO: Deprecate starting with Beryllium",
"mod",
"=",
"sys",
".",
"modules",
"[",
"name",
"]",
"if",
"not",
"hasattr",
"(",
"mod",
",",
"'__utils__'",
")",
":",
"setattr",
"(",
"mod",
",",
"'__utils__'",
",",
... | Compatibility helper function to make __utils__ available on demand. | [
"Compatibility",
"helper",
"function",
"to",
"make",
"__utils__",
"available",
"on",
"demand",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/compat.py#L18-L26 | train |
saltstack/salt | salt/utils/compat.py | deepcopy_bound | def deepcopy_bound(name):
'''
Compatibility helper function to allow copy.deepcopy copy bound methods
which is broken on Python 2.6, due to the following bug:
https://bugs.python.org/issue1515
Warnings:
- This method will mutate the global deepcopy dispatcher, which means that
this function is NOT threadsafe!
- Not Py3 compatible. The intended use case is deepcopy compat for Py2.6
'''
def _deepcopy_method(x, memo):
return type(x)(x.im_func, copy.deepcopy(x.im_self, memo), x.im_class) # pylint: disable=incompatible-py3-code
try:
pre_dispatch = copy._deepcopy_dispatch
copy._deepcopy_dispatch[types.MethodType] = _deepcopy_method
ret = copy.deepcopy(name)
finally:
copy._deepcopy_dispatch = pre_dispatch
return ret | python | def deepcopy_bound(name):
'''
Compatibility helper function to allow copy.deepcopy copy bound methods
which is broken on Python 2.6, due to the following bug:
https://bugs.python.org/issue1515
Warnings:
- This method will mutate the global deepcopy dispatcher, which means that
this function is NOT threadsafe!
- Not Py3 compatible. The intended use case is deepcopy compat for Py2.6
'''
def _deepcopy_method(x, memo):
return type(x)(x.im_func, copy.deepcopy(x.im_self, memo), x.im_class) # pylint: disable=incompatible-py3-code
try:
pre_dispatch = copy._deepcopy_dispatch
copy._deepcopy_dispatch[types.MethodType] = _deepcopy_method
ret = copy.deepcopy(name)
finally:
copy._deepcopy_dispatch = pre_dispatch
return ret | [
"def",
"deepcopy_bound",
"(",
"name",
")",
":",
"def",
"_deepcopy_method",
"(",
"x",
",",
"memo",
")",
":",
"return",
"type",
"(",
"x",
")",
"(",
"x",
".",
"im_func",
",",
"copy",
".",
"deepcopy",
"(",
"x",
".",
"im_self",
",",
"memo",
")",
",",
... | Compatibility helper function to allow copy.deepcopy copy bound methods
which is broken on Python 2.6, due to the following bug:
https://bugs.python.org/issue1515
Warnings:
- This method will mutate the global deepcopy dispatcher, which means that
this function is NOT threadsafe!
- Not Py3 compatible. The intended use case is deepcopy compat for Py2.6 | [
"Compatibility",
"helper",
"function",
"to",
"allow",
"copy",
".",
"deepcopy",
"copy",
"bound",
"methods",
"which",
"is",
"broken",
"on",
"Python",
"2",
".",
"6",
"due",
"to",
"the",
"following",
"bug",
":",
"https",
":",
"//",
"bugs",
".",
"python",
"."... | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/compat.py#L29-L50 | train |
saltstack/salt | salt/modules/pkgutil.py | upgrade_available | def upgrade_available(name):
'''
Check if there is an upgrade available for a certain package
CLI Example:
.. code-block:: bash
salt '*' pkgutil.upgrade_available CSWpython
'''
version_num = None
cmd = '/opt/csw/bin/pkgutil -c --parse --single {0}'.format(
name)
out = __salt__['cmd.run_stdout'](cmd)
if out:
version_num = out.split()[2].strip()
if version_num:
if version_num == "SAME":
return ''
else:
return version_num
return '' | python | def upgrade_available(name):
'''
Check if there is an upgrade available for a certain package
CLI Example:
.. code-block:: bash
salt '*' pkgutil.upgrade_available CSWpython
'''
version_num = None
cmd = '/opt/csw/bin/pkgutil -c --parse --single {0}'.format(
name)
out = __salt__['cmd.run_stdout'](cmd)
if out:
version_num = out.split()[2].strip()
if version_num:
if version_num == "SAME":
return ''
else:
return version_num
return '' | [
"def",
"upgrade_available",
"(",
"name",
")",
":",
"version_num",
"=",
"None",
"cmd",
"=",
"'/opt/csw/bin/pkgutil -c --parse --single {0}'",
".",
"format",
"(",
"name",
")",
"out",
"=",
"__salt__",
"[",
"'cmd.run_stdout'",
"]",
"(",
"cmd",
")",
"if",
"out",
":... | Check if there is an upgrade available for a certain package
CLI Example:
.. code-block:: bash
salt '*' pkgutil.upgrade_available CSWpython | [
"Check",
"if",
"there",
"is",
"an",
"upgrade",
"available",
"for",
"a",
"certain",
"package"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pkgutil.py#L53-L74 | train |
saltstack/salt | salt/modules/pkgutil.py | list_upgrades | def list_upgrades(refresh=True, **kwargs): # pylint: disable=W0613
'''
List all available package upgrades on this system
CLI Example:
.. code-block:: bash
salt '*' pkgutil.list_upgrades
'''
if salt.utils.data.is_true(refresh):
refresh_db()
upgrades = {}
lines = __salt__['cmd.run_stdout'](
'/opt/csw/bin/pkgutil -A --parse').splitlines()
for line in lines:
comps = line.split('\t')
if comps[2] == "SAME":
continue
if comps[2] == "not installed":
continue
upgrades[comps[0]] = comps[1]
return upgrades | python | def list_upgrades(refresh=True, **kwargs): # pylint: disable=W0613
'''
List all available package upgrades on this system
CLI Example:
.. code-block:: bash
salt '*' pkgutil.list_upgrades
'''
if salt.utils.data.is_true(refresh):
refresh_db()
upgrades = {}
lines = __salt__['cmd.run_stdout'](
'/opt/csw/bin/pkgutil -A --parse').splitlines()
for line in lines:
comps = line.split('\t')
if comps[2] == "SAME":
continue
if comps[2] == "not installed":
continue
upgrades[comps[0]] = comps[1]
return upgrades | [
"def",
"list_upgrades",
"(",
"refresh",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=W0613",
"if",
"salt",
".",
"utils",
".",
"data",
".",
"is_true",
"(",
"refresh",
")",
":",
"refresh_db",
"(",
")",
"upgrades",
"=",
"{",
"}",
"li... | List all available package upgrades on this system
CLI Example:
.. code-block:: bash
salt '*' pkgutil.list_upgrades | [
"List",
"all",
"available",
"package",
"upgrades",
"on",
"this",
"system"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pkgutil.py#L77-L99 | train |
saltstack/salt | salt/modules/pkgutil.py | upgrade | def upgrade(refresh=True):
'''
Upgrade all of the packages to the latest available version.
Returns a dict containing the changes::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkgutil.upgrade
'''
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
# Install or upgrade the package
# If package is already installed
cmd = '/opt/csw/bin/pkgutil -yu'
__salt__['cmd.run_all'](cmd)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new) | python | def upgrade(refresh=True):
'''
Upgrade all of the packages to the latest available version.
Returns a dict containing the changes::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkgutil.upgrade
'''
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
# Install or upgrade the package
# If package is already installed
cmd = '/opt/csw/bin/pkgutil -yu'
__salt__['cmd.run_all'](cmd)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new) | [
"def",
"upgrade",
"(",
"refresh",
"=",
"True",
")",
":",
"if",
"salt",
".",
"utils",
".",
"data",
".",
"is_true",
"(",
"refresh",
")",
":",
"refresh_db",
"(",
")",
"old",
"=",
"list_pkgs",
"(",
")",
"# Install or upgrade the package",
"# If package is alread... | Upgrade all of the packages to the latest available version.
Returns a dict containing the changes::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkgutil.upgrade | [
"Upgrade",
"all",
"of",
"the",
"packages",
"to",
"the",
"latest",
"available",
"version",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pkgutil.py#L102-L128 | train |
saltstack/salt | salt/modules/pkgutil.py | install | def install(name=None, refresh=False, version=None, pkgs=None, **kwargs):
'''
Install packages using the pkgutil tool.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package_name>
salt '*' pkg.install SMClgcc346
Multiple Package Installation Options:
pkgs
A list of packages to install from OpenCSW. Must be passed as a python
list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3"}]'
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
if refresh:
refresh_db()
try:
# Ignore 'sources' argument
pkg_params = __salt__['pkg_resource.parse_targets'](name,
pkgs,
**kwargs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
if pkgs is None and version and len(pkg_params) == 1:
pkg_params = {name: version}
targets = []
for param, pkgver in six.iteritems(pkg_params):
if pkgver is None:
targets.append(param)
else:
targets.append('{0}-{1}'.format(param, pkgver))
cmd = '/opt/csw/bin/pkgutil -yu {0}'.format(' '.join(targets))
old = list_pkgs()
__salt__['cmd.run_all'](cmd)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new) | python | def install(name=None, refresh=False, version=None, pkgs=None, **kwargs):
'''
Install packages using the pkgutil tool.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package_name>
salt '*' pkg.install SMClgcc346
Multiple Package Installation Options:
pkgs
A list of packages to install from OpenCSW. Must be passed as a python
list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3"}]'
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
if refresh:
refresh_db()
try:
# Ignore 'sources' argument
pkg_params = __salt__['pkg_resource.parse_targets'](name,
pkgs,
**kwargs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
if not pkg_params:
return {}
if pkgs is None and version and len(pkg_params) == 1:
pkg_params = {name: version}
targets = []
for param, pkgver in six.iteritems(pkg_params):
if pkgver is None:
targets.append(param)
else:
targets.append('{0}-{1}'.format(param, pkgver))
cmd = '/opt/csw/bin/pkgutil -yu {0}'.format(' '.join(targets))
old = list_pkgs()
__salt__['cmd.run_all'](cmd)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new) | [
"def",
"install",
"(",
"name",
"=",
"None",
",",
"refresh",
"=",
"False",
",",
"version",
"=",
"None",
",",
"pkgs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"refresh",
":",
"refresh_db",
"(",
")",
"try",
":",
"# Ignore 'sources' argument",... | Install packages using the pkgutil tool.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package_name>
salt '*' pkg.install SMClgcc346
Multiple Package Installation Options:
pkgs
A list of packages to install from OpenCSW. Must be passed as a python
list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3"}]'
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}} | [
"Install",
"packages",
"using",
"the",
"pkgutil",
"tool",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pkgutil.py#L248-L307 | train |
saltstack/salt | salt/modules/pkgutil.py | remove | def remove(name=None, pkgs=None, **kwargs):
'''
Remove a package and all its dependencies which are not in use by other
packages.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
targets = [x for x in pkg_params if x in old]
if not targets:
return {}
cmd = '/opt/csw/bin/pkgutil -yr {0}'.format(' '.join(targets))
__salt__['cmd.run_all'](cmd)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new) | python | def remove(name=None, pkgs=None, **kwargs):
'''
Remove a package and all its dependencies which are not in use by other
packages.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
targets = [x for x in pkg_params if x in old]
if not targets:
return {}
cmd = '/opt/csw/bin/pkgutil -yr {0}'.format(' '.join(targets))
__salt__['cmd.run_all'](cmd)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new) | [
"def",
"remove",
"(",
"name",
"=",
"None",
",",
"pkgs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"pkg_params",
"=",
"__salt__",
"[",
"'pkg_resource.parse_targets'",
"]",
"(",
"name",
",",
"pkgs",
")",
"[",
"0",
"]",
"except",
"Mini... | Remove a package and all its dependencies which are not in use by other
packages.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
.. versionadded:: 0.16.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]' | [
"Remove",
"a",
"package",
"and",
"all",
"its",
"dependencies",
"which",
"are",
"not",
"in",
"use",
"by",
"other",
"packages",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pkgutil.py#L310-L351 | train |
saltstack/salt | salt/states/zenoss.py | monitored | def monitored(name, device_class=None, collector='localhost', prod_state=None):
'''
Ensure a device is monitored. The 'name' given will be used for Zenoss device name and should be resolvable.
.. code-block:: yaml
enable_monitoring:
zenoss.monitored:
- name: web01.example.com
- device_class: /Servers/Linux
- collector: localhost
- prod_state: 1000
'''
ret = {}
ret['name'] = name
# If device is already monitored, return early
device = __salt__['zenoss.find_device'](name)
if device:
ret['result'] = True
ret['changes'] = None
ret['comment'] = '{0} is already monitored'.format(name)
# if prod_state is set, ensure it matches with the current state
if prod_state is not None and device['productionState'] != prod_state:
if __opts__['test']:
ret['comment'] = '{0} is already monitored but prodState will be updated'.format(name)
ret['result'] = None
else:
__salt__['zenoss.set_prod_state'](prod_state, name)
ret['comment'] = '{0} is already monitored but prodState was updated'.format(name)
ret['changes'] = {
'old': 'prodState == {0}'.format(device['productionState']),
'new': 'prodState == {0}'.format(prod_state)
}
return ret
# Device not yet in Zenoss
if __opts__['test']:
ret['comment'] = 'The state of "{0}" will be changed.'.format(name)
ret['changes'] = {'old': 'monitored == False', 'new': 'monitored == True'}
ret['result'] = None
return ret
# Add and check result
if __salt__['zenoss.add_device'](name, device_class, collector, prod_state):
ret['result'] = True
ret['changes'] = {'old': 'monitored == False', 'new': 'monitored == True'}
ret['comment'] = '{0} has been added to Zenoss'.format(name)
else:
ret['result'] = False
ret['changes'] = None
ret['comment'] = 'Unable to add {0} to Zenoss'.format(name)
return ret | python | def monitored(name, device_class=None, collector='localhost', prod_state=None):
'''
Ensure a device is monitored. The 'name' given will be used for Zenoss device name and should be resolvable.
.. code-block:: yaml
enable_monitoring:
zenoss.monitored:
- name: web01.example.com
- device_class: /Servers/Linux
- collector: localhost
- prod_state: 1000
'''
ret = {}
ret['name'] = name
# If device is already monitored, return early
device = __salt__['zenoss.find_device'](name)
if device:
ret['result'] = True
ret['changes'] = None
ret['comment'] = '{0} is already monitored'.format(name)
# if prod_state is set, ensure it matches with the current state
if prod_state is not None and device['productionState'] != prod_state:
if __opts__['test']:
ret['comment'] = '{0} is already monitored but prodState will be updated'.format(name)
ret['result'] = None
else:
__salt__['zenoss.set_prod_state'](prod_state, name)
ret['comment'] = '{0} is already monitored but prodState was updated'.format(name)
ret['changes'] = {
'old': 'prodState == {0}'.format(device['productionState']),
'new': 'prodState == {0}'.format(prod_state)
}
return ret
# Device not yet in Zenoss
if __opts__['test']:
ret['comment'] = 'The state of "{0}" will be changed.'.format(name)
ret['changes'] = {'old': 'monitored == False', 'new': 'monitored == True'}
ret['result'] = None
return ret
# Add and check result
if __salt__['zenoss.add_device'](name, device_class, collector, prod_state):
ret['result'] = True
ret['changes'] = {'old': 'monitored == False', 'new': 'monitored == True'}
ret['comment'] = '{0} has been added to Zenoss'.format(name)
else:
ret['result'] = False
ret['changes'] = None
ret['comment'] = 'Unable to add {0} to Zenoss'.format(name)
return ret | [
"def",
"monitored",
"(",
"name",
",",
"device_class",
"=",
"None",
",",
"collector",
"=",
"'localhost'",
",",
"prod_state",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"}",
"ret",
"[",
"'name'",
"]",
"=",
"name",
"# If device is already monitored, return early",
... | Ensure a device is monitored. The 'name' given will be used for Zenoss device name and should be resolvable.
.. code-block:: yaml
enable_monitoring:
zenoss.monitored:
- name: web01.example.com
- device_class: /Servers/Linux
- collector: localhost
- prod_state: 1000 | [
"Ensure",
"a",
"device",
"is",
"monitored",
".",
"The",
"name",
"given",
"will",
"be",
"used",
"for",
"Zenoss",
"device",
"name",
"and",
"should",
"be",
"resolvable",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/zenoss.py#L37-L92 | train |
saltstack/salt | salt/states/docker_volume.py | _find_volume | def _find_volume(name):
'''
Find volume by name on minion
'''
docker_volumes = __salt__['docker.volumes']()['Volumes']
if docker_volumes:
volumes = [v for v in docker_volumes if v['Name'] == name]
if volumes:
return volumes[0]
return None | python | def _find_volume(name):
'''
Find volume by name on minion
'''
docker_volumes = __salt__['docker.volumes']()['Volumes']
if docker_volumes:
volumes = [v for v in docker_volumes if v['Name'] == name]
if volumes:
return volumes[0]
return None | [
"def",
"_find_volume",
"(",
"name",
")",
":",
"docker_volumes",
"=",
"__salt__",
"[",
"'docker.volumes'",
"]",
"(",
")",
"[",
"'Volumes'",
"]",
"if",
"docker_volumes",
":",
"volumes",
"=",
"[",
"v",
"for",
"v",
"in",
"docker_volumes",
"if",
"v",
"[",
"'N... | Find volume by name on minion | [
"Find",
"volume",
"by",
"name",
"on",
"minion"
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/docker_volume.py#L56-L66 | train |
saltstack/salt | salt/states/docker_volume.py | present | def present(name, driver=None, driver_opts=None, force=False):
'''
Ensure that a volume is present.
.. versionadded:: 2015.8.4
.. versionchanged:: 2015.8.6
This state no longer deletes and re-creates a volume if the existing
volume's driver does not match the ``driver`` parameter (unless the
``force`` parameter is set to ``True``).
.. versionchanged:: 2017.7.0
This state was renamed from **docker.volume_present** to **docker_volume.present**
name
Name of the volume
driver
Type of driver for that volume. If ``None`` and the volume
does not yet exist, the volume will be created using Docker's
default driver. If ``None`` and the volume does exist, this
function does nothing, even if the existing volume's driver is
not the Docker default driver. (To ensure that an existing
volume's driver matches the Docker default, you must
explicitly name Docker's default driver here.)
driver_opts
Options for the volume driver
force : False
If the volume already exists but the existing volume's driver
does not match the driver specified by the ``driver``
parameter, this parameter controls whether the function errors
out (if ``False``) or deletes and re-creates the volume (if
``True``).
.. versionadded:: 2015.8.6
Usage Examples:
.. code-block:: yaml
volume_foo:
docker_volume.present
.. code-block:: yaml
volume_bar:
docker_volume.present
- name: bar
- driver: local
- driver_opts:
foo: bar
.. code-block:: yaml
volume_bar:
docker_volume.present
- name: bar
- driver: local
- driver_opts:
- foo: bar
- option: value
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if salt.utils.data.is_dictlist(driver_opts):
driver_opts = salt.utils.data.repack_dictlist(driver_opts)
volume = _find_volume(name)
if not volume:
if __opts__['test']:
ret['result'] = None
ret['comment'] = ('The volume \'{0}\' will be created'.format(name))
return ret
try:
ret['changes']['created'] = __salt__['docker.create_volume'](
name, driver=driver, driver_opts=driver_opts)
except Exception as exc:
ret['comment'] = ('Failed to create volume \'{0}\': {1}'
.format(name, exc))
return ret
else:
result = True
ret['result'] = result
return ret
# volume exists, check if driver is the same.
if driver is not None and volume['Driver'] != driver:
if not force:
ret['comment'] = "Driver for existing volume '{0}' ('{1}')" \
" does not match specified driver ('{2}')" \
" and force is False".format(
name, volume['Driver'], driver)
ret['result'] = None if __opts__['test'] else False
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = "The volume '{0}' will be replaced with a" \
" new one using the driver '{1}'".format(
name, volume)
return ret
try:
ret['changes']['removed'] = __salt__['docker.remove_volume'](name)
except Exception as exc:
ret['comment'] = ('Failed to remove volume \'{0}\': {1}'
.format(name, exc))
return ret
else:
try:
ret['changes']['created'] = __salt__['docker.create_volume'](
name, driver=driver, driver_opts=driver_opts)
except Exception as exc:
ret['comment'] = ('Failed to create volume \'{0}\': {1}'
.format(name, exc))
return ret
else:
result = True
ret['result'] = result
return ret
ret['result'] = True
ret['comment'] = 'Volume \'{0}\' already exists.'.format(name)
return ret | python | def present(name, driver=None, driver_opts=None, force=False):
'''
Ensure that a volume is present.
.. versionadded:: 2015.8.4
.. versionchanged:: 2015.8.6
This state no longer deletes and re-creates a volume if the existing
volume's driver does not match the ``driver`` parameter (unless the
``force`` parameter is set to ``True``).
.. versionchanged:: 2017.7.0
This state was renamed from **docker.volume_present** to **docker_volume.present**
name
Name of the volume
driver
Type of driver for that volume. If ``None`` and the volume
does not yet exist, the volume will be created using Docker's
default driver. If ``None`` and the volume does exist, this
function does nothing, even if the existing volume's driver is
not the Docker default driver. (To ensure that an existing
volume's driver matches the Docker default, you must
explicitly name Docker's default driver here.)
driver_opts
Options for the volume driver
force : False
If the volume already exists but the existing volume's driver
does not match the driver specified by the ``driver``
parameter, this parameter controls whether the function errors
out (if ``False``) or deletes and re-creates the volume (if
``True``).
.. versionadded:: 2015.8.6
Usage Examples:
.. code-block:: yaml
volume_foo:
docker_volume.present
.. code-block:: yaml
volume_bar:
docker_volume.present
- name: bar
- driver: local
- driver_opts:
foo: bar
.. code-block:: yaml
volume_bar:
docker_volume.present
- name: bar
- driver: local
- driver_opts:
- foo: bar
- option: value
'''
ret = {'name': name,
'changes': {},
'result': False,
'comment': ''}
if salt.utils.data.is_dictlist(driver_opts):
driver_opts = salt.utils.data.repack_dictlist(driver_opts)
volume = _find_volume(name)
if not volume:
if __opts__['test']:
ret['result'] = None
ret['comment'] = ('The volume \'{0}\' will be created'.format(name))
return ret
try:
ret['changes']['created'] = __salt__['docker.create_volume'](
name, driver=driver, driver_opts=driver_opts)
except Exception as exc:
ret['comment'] = ('Failed to create volume \'{0}\': {1}'
.format(name, exc))
return ret
else:
result = True
ret['result'] = result
return ret
# volume exists, check if driver is the same.
if driver is not None and volume['Driver'] != driver:
if not force:
ret['comment'] = "Driver for existing volume '{0}' ('{1}')" \
" does not match specified driver ('{2}')" \
" and force is False".format(
name, volume['Driver'], driver)
ret['result'] = None if __opts__['test'] else False
return ret
if __opts__['test']:
ret['result'] = None
ret['comment'] = "The volume '{0}' will be replaced with a" \
" new one using the driver '{1}'".format(
name, volume)
return ret
try:
ret['changes']['removed'] = __salt__['docker.remove_volume'](name)
except Exception as exc:
ret['comment'] = ('Failed to remove volume \'{0}\': {1}'
.format(name, exc))
return ret
else:
try:
ret['changes']['created'] = __salt__['docker.create_volume'](
name, driver=driver, driver_opts=driver_opts)
except Exception as exc:
ret['comment'] = ('Failed to create volume \'{0}\': {1}'
.format(name, exc))
return ret
else:
result = True
ret['result'] = result
return ret
ret['result'] = True
ret['comment'] = 'Volume \'{0}\' already exists.'.format(name)
return ret | [
"def",
"present",
"(",
"name",
",",
"driver",
"=",
"None",
",",
"driver_opts",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"False",
",",
"'comment... | Ensure that a volume is present.
.. versionadded:: 2015.8.4
.. versionchanged:: 2015.8.6
This state no longer deletes and re-creates a volume if the existing
volume's driver does not match the ``driver`` parameter (unless the
``force`` parameter is set to ``True``).
.. versionchanged:: 2017.7.0
This state was renamed from **docker.volume_present** to **docker_volume.present**
name
Name of the volume
driver
Type of driver for that volume. If ``None`` and the volume
does not yet exist, the volume will be created using Docker's
default driver. If ``None`` and the volume does exist, this
function does nothing, even if the existing volume's driver is
not the Docker default driver. (To ensure that an existing
volume's driver matches the Docker default, you must
explicitly name Docker's default driver here.)
driver_opts
Options for the volume driver
force : False
If the volume already exists but the existing volume's driver
does not match the driver specified by the ``driver``
parameter, this parameter controls whether the function errors
out (if ``False``) or deletes and re-creates the volume (if
``True``).
.. versionadded:: 2015.8.6
Usage Examples:
.. code-block:: yaml
volume_foo:
docker_volume.present
.. code-block:: yaml
volume_bar:
docker_volume.present
- name: bar
- driver: local
- driver_opts:
foo: bar
.. code-block:: yaml
volume_bar:
docker_volume.present
- name: bar
- driver: local
- driver_opts:
- foo: bar
- option: value | [
"Ensure",
"that",
"a",
"volume",
"is",
"present",
"."
] | e8541fd6e744ab0df786c0f76102e41631f45d46 | https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/docker_volume.py#L69-L192 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.