repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
saltstack/salt
salt/modules/useradd.py
_format_info
def _format_info(data): ''' Return user information in a pretty way ''' # Put GECOS info into a list gecos_field = salt.utils.stringutils.to_unicode(data.pw_gecos).split(',', 4) # Make sure our list has at least five elements while len(gecos_field) < 5: gecos_field.append('') return {'gid': data.pw_gid, 'groups': list_groups(data.pw_name), 'home': data.pw_dir, 'name': data.pw_name, 'passwd': data.pw_passwd, 'shell': data.pw_shell, 'uid': data.pw_uid, 'fullname': gecos_field[0], 'roomnumber': gecos_field[1], 'workphone': gecos_field[2], 'homephone': gecos_field[3], 'other': gecos_field[4]}
python
def _format_info(data): ''' Return user information in a pretty way ''' # Put GECOS info into a list gecos_field = salt.utils.stringutils.to_unicode(data.pw_gecos).split(',', 4) # Make sure our list has at least five elements while len(gecos_field) < 5: gecos_field.append('') return {'gid': data.pw_gid, 'groups': list_groups(data.pw_name), 'home': data.pw_dir, 'name': data.pw_name, 'passwd': data.pw_passwd, 'shell': data.pw_shell, 'uid': data.pw_uid, 'fullname': gecos_field[0], 'roomnumber': gecos_field[1], 'workphone': gecos_field[2], 'homephone': gecos_field[3], 'other': gecos_field[4]}
[ "def", "_format_info", "(", "data", ")", ":", "# Put GECOS info into a list", "gecos_field", "=", "salt", ".", "utils", ".", "stringutils", ".", "to_unicode", "(", "data", ".", "pw_gecos", ")", ".", "split", "(", "','", ",", "4", ")", "# Make sure our list has...
Return user information in a pretty way
[ "Return", "user", "information", "in", "a", "pretty", "way" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/useradd.py#L793-L814
train
saltstack/salt
salt/modules/useradd.py
list_users
def list_users(root=None): ''' Return a list of all users root Directory to chroot into CLI Example: .. code-block:: bash salt '*' user.list_users ''' if root is not None and __grains__['kernel'] != 'AIX': getpwall = functools.partial(_getpwall, root=root) else: getpwall = functools.partial(pwd.getpwall) return sorted([user.pw_name for user in getpwall()])
python
def list_users(root=None): ''' Return a list of all users root Directory to chroot into CLI Example: .. code-block:: bash salt '*' user.list_users ''' if root is not None and __grains__['kernel'] != 'AIX': getpwall = functools.partial(_getpwall, root=root) else: getpwall = functools.partial(pwd.getpwall) return sorted([user.pw_name for user in getpwall()])
[ "def", "list_users", "(", "root", "=", "None", ")", ":", "if", "root", "is", "not", "None", "and", "__grains__", "[", "'kernel'", "]", "!=", "'AIX'", ":", "getpwall", "=", "functools", ".", "partial", "(", "_getpwall", ",", "root", "=", "root", ")", ...
Return a list of all users root Directory to chroot into CLI Example: .. code-block:: bash salt '*' user.list_users
[ "Return", "a", "list", "of", "all", "users" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/useradd.py#L852-L870
train
saltstack/salt
salt/modules/useradd.py
rename
def rename(name, new_name, root=None): ''' Change the username for a named user name User to modify new_name New value of the login name root Directory to chroot into CLI Example: .. code-block:: bash salt '*' user.rename name new_name ''' if info(new_name, root=root): raise CommandExecutionError('User \'{0}\' already exists'.format(new_name)) return _chattrib(name, 'name', new_name, '-l', root=root)
python
def rename(name, new_name, root=None): ''' Change the username for a named user name User to modify new_name New value of the login name root Directory to chroot into CLI Example: .. code-block:: bash salt '*' user.rename name new_name ''' if info(new_name, root=root): raise CommandExecutionError('User \'{0}\' already exists'.format(new_name)) return _chattrib(name, 'name', new_name, '-l', root=root)
[ "def", "rename", "(", "name", ",", "new_name", ",", "root", "=", "None", ")", ":", "if", "info", "(", "new_name", ",", "root", "=", "root", ")", ":", "raise", "CommandExecutionError", "(", "'User \\'{0}\\' already exists'", ".", "format", "(", "new_name", ...
Change the username for a named user name User to modify new_name New value of the login name root Directory to chroot into CLI Example: .. code-block:: bash salt '*' user.rename name new_name
[ "Change", "the", "username", "for", "a", "named", "user" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/useradd.py#L873-L895
train
saltstack/salt
salt/modules/useradd.py
_getpwnam
def _getpwnam(name, root=None): ''' Alternative implementation for getpwnam, that use only /etc/passwd ''' root = '/' if not root else root passwd = os.path.join(root, 'etc/passwd') with salt.utils.files.fopen(passwd) as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) comps = line.strip().split(':') if comps[0] == name: # Generate a getpwnam compatible output comps[2], comps[3] = int(comps[2]), int(comps[3]) return pwd.struct_passwd(comps) raise KeyError
python
def _getpwnam(name, root=None): ''' Alternative implementation for getpwnam, that use only /etc/passwd ''' root = '/' if not root else root passwd = os.path.join(root, 'etc/passwd') with salt.utils.files.fopen(passwd) as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) comps = line.strip().split(':') if comps[0] == name: # Generate a getpwnam compatible output comps[2], comps[3] = int(comps[2]), int(comps[3]) return pwd.struct_passwd(comps) raise KeyError
[ "def", "_getpwnam", "(", "name", ",", "root", "=", "None", ")", ":", "root", "=", "'/'", "if", "not", "root", "else", "root", "passwd", "=", "os", ".", "path", ".", "join", "(", "root", ",", "'etc/passwd'", ")", "with", "salt", ".", "utils", ".", ...
Alternative implementation for getpwnam, that use only /etc/passwd
[ "Alternative", "implementation", "for", "getpwnam", "that", "use", "only", "/", "etc", "/", "passwd" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/useradd.py#L898-L912
train
saltstack/salt
salt/modules/useradd.py
add_subgids
def add_subgids(name, first=100000, last=110000): ''' Add a range of subordinate gids to the user name User to modify first Begin of the range last End of the range CLI Examples: .. code-block:: bash salt '*' user.add_subgids foo salt '*' user.add_subgids foo first=105000 salt '*' user.add_subgids foo first=600000000 last=600100000 ''' if __grains__['kernel'] != 'Linux': log.warning("'subgids' are only supported on GNU/Linux hosts.") return __salt__['cmd.run'](['usermod', '-w', '-'.join(str(x) for x in (first, last)), name])
python
def add_subgids(name, first=100000, last=110000): ''' Add a range of subordinate gids to the user name User to modify first Begin of the range last End of the range CLI Examples: .. code-block:: bash salt '*' user.add_subgids foo salt '*' user.add_subgids foo first=105000 salt '*' user.add_subgids foo first=600000000 last=600100000 ''' if __grains__['kernel'] != 'Linux': log.warning("'subgids' are only supported on GNU/Linux hosts.") return __salt__['cmd.run'](['usermod', '-w', '-'.join(str(x) for x in (first, last)), name])
[ "def", "add_subgids", "(", "name", ",", "first", "=", "100000", ",", "last", "=", "110000", ")", ":", "if", "__grains__", "[", "'kernel'", "]", "!=", "'Linux'", ":", "log", ".", "warning", "(", "\"'subgids' are only supported on GNU/Linux hosts.\"", ")", "retu...
Add a range of subordinate gids to the user name User to modify first Begin of the range last End of the range CLI Examples: .. code-block:: bash salt '*' user.add_subgids foo salt '*' user.add_subgids foo first=105000 salt '*' user.add_subgids foo first=600000000 last=600100000
[ "Add", "a", "range", "of", "subordinate", "gids", "to", "the", "user" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/useradd.py#L984-L1008
train
saltstack/salt
salt/states/win_dism.py
capability_installed
def capability_installed(name, source=None, limit_access=False, image=None, restart=False): ''' Install a DISM capability Args: name (str): The capability to install source (str): The optional source of the capability limit_access (bool): Prevent DISM from contacting Windows Update for online images image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Example: Run ``dism.available_capabilities`` to get a list of available capabilities. This will help you get the proper name to use. .. code-block:: yaml install_dotnet35: dism.capability_installed: - name: NetFX3~~~~ ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} old = __salt__['dism.installed_capabilities']() if name in old: ret['comment'] = 'The capability {0} is already installed'.format(name) return ret if __opts__['test']: ret['changes']['capability'] = '{0} will be installed'.format(name) ret['result'] = None return ret # Install the capability status = __salt__['dism.add_capability']( name, source, limit_access, image, restart) if status['retcode'] not in [0, 1641, 3010]: ret['comment'] = 'Failed to install {0}: {1}'\ .format(name, status['stdout']) ret['result'] = False new = __salt__['dism.installed_capabilities']() changes = salt.utils.data.compare_lists(old, new) if changes: ret['comment'] = 'Installed {0}'.format(name) ret['changes'] = status ret['changes']['capability'] = changes return ret
python
def capability_installed(name, source=None, limit_access=False, image=None, restart=False): ''' Install a DISM capability Args: name (str): The capability to install source (str): The optional source of the capability limit_access (bool): Prevent DISM from contacting Windows Update for online images image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Example: Run ``dism.available_capabilities`` to get a list of available capabilities. This will help you get the proper name to use. .. code-block:: yaml install_dotnet35: dism.capability_installed: - name: NetFX3~~~~ ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} old = __salt__['dism.installed_capabilities']() if name in old: ret['comment'] = 'The capability {0} is already installed'.format(name) return ret if __opts__['test']: ret['changes']['capability'] = '{0} will be installed'.format(name) ret['result'] = None return ret # Install the capability status = __salt__['dism.add_capability']( name, source, limit_access, image, restart) if status['retcode'] not in [0, 1641, 3010]: ret['comment'] = 'Failed to install {0}: {1}'\ .format(name, status['stdout']) ret['result'] = False new = __salt__['dism.installed_capabilities']() changes = salt.utils.data.compare_lists(old, new) if changes: ret['comment'] = 'Installed {0}'.format(name) ret['changes'] = status ret['changes']['capability'] = changes return ret
[ "def", "capability_installed", "(", "name", ",", "source", "=", "None", ",", "limit_access", "=", "False", ",", "image", "=", "None", ",", "restart", "=", "False", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "...
Install a DISM capability Args: name (str): The capability to install source (str): The optional source of the capability limit_access (bool): Prevent DISM from contacting Windows Update for online images image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Example: Run ``dism.available_capabilities`` to get a list of available capabilities. This will help you get the proper name to use. .. code-block:: yaml install_dotnet35: dism.capability_installed: - name: NetFX3~~~~
[ "Install", "a", "DISM", "capability" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_dism.py#L40-L101
train
saltstack/salt
salt/states/win_dism.py
package_removed
def package_removed(name, image=None, restart=False): ''' Uninstall a package Args: name (str): The full path to the package. Can be either a .cab file or a folder. Should point to the original source of the package, not to where the file is installed. This can also be the name of a package as listed in ``dism.installed_packages`` image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Example: .. code-block:: yaml # Example using source remove_KB1231231: dism.package_installed: - name: C:\\Packages\\KB1231231.cab # Example using name from ``dism.installed_packages`` remove_KB1231231: dism.package_installed: - name: Package_for_KB1231231~31bf3856ad364e35~amd64~~10.0.1.3 ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} # Fail if using a non-existent package path if '~' not in name and not os.path.exists(name): if __opts__['test']: ret['result'] = None else: ret['result'] = False ret['comment'] = 'Package path {0} does not exist'.format(name) return ret old = __salt__['dism.installed_packages']() # Get package info so we can see if it's already removed package_info = __salt__['dism.package_info'](name) # If `Package Identity` isn't returned or if they passed a cab file, if # `Package Identity` isn't in the list of installed packages if 'Package Identity' not in package_info or \ package_info['Package Identity'] not in old: ret['comment'] = 'The package {0} is already removed'.format(name) return ret if __opts__['test']: ret['changes']['package'] = '{0} will be removed'.format(name) ret['result'] = None return ret # Remove the package status = __salt__['dism.remove_package'](name, image, restart) if status['retcode'] not in [0, 1641, 3010]: ret['comment'] = 'Failed to remove {0}: {1}' \ .format(name, status['stdout']) ret['result'] = False new = __salt__['dism.installed_packages']() changes = salt.utils.data.compare_lists(old, new) if changes: ret['comment'] = 'Removed {0}'.format(name) ret['changes'] = status ret['changes']['package'] = changes return ret
python
def package_removed(name, image=None, restart=False): ''' Uninstall a package Args: name (str): The full path to the package. Can be either a .cab file or a folder. Should point to the original source of the package, not to where the file is installed. This can also be the name of a package as listed in ``dism.installed_packages`` image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Example: .. code-block:: yaml # Example using source remove_KB1231231: dism.package_installed: - name: C:\\Packages\\KB1231231.cab # Example using name from ``dism.installed_packages`` remove_KB1231231: dism.package_installed: - name: Package_for_KB1231231~31bf3856ad364e35~amd64~~10.0.1.3 ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} # Fail if using a non-existent package path if '~' not in name and not os.path.exists(name): if __opts__['test']: ret['result'] = None else: ret['result'] = False ret['comment'] = 'Package path {0} does not exist'.format(name) return ret old = __salt__['dism.installed_packages']() # Get package info so we can see if it's already removed package_info = __salt__['dism.package_info'](name) # If `Package Identity` isn't returned or if they passed a cab file, if # `Package Identity` isn't in the list of installed packages if 'Package Identity' not in package_info or \ package_info['Package Identity'] not in old: ret['comment'] = 'The package {0} is already removed'.format(name) return ret if __opts__['test']: ret['changes']['package'] = '{0} will be removed'.format(name) ret['result'] = None return ret # Remove the package status = __salt__['dism.remove_package'](name, image, restart) if status['retcode'] not in [0, 1641, 3010]: ret['comment'] = 'Failed to remove {0}: {1}' \ .format(name, status['stdout']) ret['result'] = False new = __salt__['dism.installed_packages']() changes = salt.utils.data.compare_lists(old, new) if changes: ret['comment'] = 'Removed {0}'.format(name) ret['changes'] = status ret['changes']['package'] = changes return ret
[ "def", "package_removed", "(", "name", ",", "image", "=", "None", ",", "restart", "=", "False", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{", "}", "}", "# Fa...
Uninstall a package Args: name (str): The full path to the package. Can be either a .cab file or a folder. Should point to the original source of the package, not to where the file is installed. This can also be the name of a package as listed in ``dism.installed_packages`` image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. restart (Optional[bool]): Reboot the machine if required by the install Example: .. code-block:: yaml # Example using source remove_KB1231231: dism.package_installed: - name: C:\\Packages\\KB1231231.cab # Example using name from ``dism.installed_packages`` remove_KB1231231: dism.package_installed: - name: Package_for_KB1231231~31bf3856ad364e35~amd64~~10.0.1.3
[ "Uninstall", "a", "package" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_dism.py#L368-L443
train
saltstack/salt
salt/modules/network.py
ping
def ping(host, timeout=False, return_boolean=False): ''' Performs an ICMP ping to a host .. versionchanged:: 2015.8.0 Added support for SunOS CLI Example: .. code-block:: bash salt '*' network.ping archlinux.org .. versionadded:: 2015.5.0 Return a True or False instead of ping output. .. code-block:: bash salt '*' network.ping archlinux.org return_boolean=True Set the time to wait for a response in seconds. .. code-block:: bash salt '*' network.ping archlinux.org timeout=3 ''' if timeout: if __grains__['kernel'] == 'SunOS': cmd = 'ping -c 4 {1} {0}'.format(timeout, salt.utils.network.sanitize_host(host)) else: cmd = 'ping -W {0} -c 4 {1}'.format(timeout, salt.utils.network.sanitize_host(host)) else: cmd = 'ping -c 4 {0}'.format(salt.utils.network.sanitize_host(host)) if return_boolean: ret = __salt__['cmd.run_all'](cmd) if ret['retcode'] != 0: return False else: return True else: return __salt__['cmd.run'](cmd)
python
def ping(host, timeout=False, return_boolean=False): ''' Performs an ICMP ping to a host .. versionchanged:: 2015.8.0 Added support for SunOS CLI Example: .. code-block:: bash salt '*' network.ping archlinux.org .. versionadded:: 2015.5.0 Return a True or False instead of ping output. .. code-block:: bash salt '*' network.ping archlinux.org return_boolean=True Set the time to wait for a response in seconds. .. code-block:: bash salt '*' network.ping archlinux.org timeout=3 ''' if timeout: if __grains__['kernel'] == 'SunOS': cmd = 'ping -c 4 {1} {0}'.format(timeout, salt.utils.network.sanitize_host(host)) else: cmd = 'ping -W {0} -c 4 {1}'.format(timeout, salt.utils.network.sanitize_host(host)) else: cmd = 'ping -c 4 {0}'.format(salt.utils.network.sanitize_host(host)) if return_boolean: ret = __salt__['cmd.run_all'](cmd) if ret['retcode'] != 0: return False else: return True else: return __salt__['cmd.run'](cmd)
[ "def", "ping", "(", "host", ",", "timeout", "=", "False", ",", "return_boolean", "=", "False", ")", ":", "if", "timeout", ":", "if", "__grains__", "[", "'kernel'", "]", "==", "'SunOS'", ":", "cmd", "=", "'ping -c 4 {1} {0}'", ".", "format", "(", "timeout...
Performs an ICMP ping to a host .. versionchanged:: 2015.8.0 Added support for SunOS CLI Example: .. code-block:: bash salt '*' network.ping archlinux.org .. versionadded:: 2015.5.0 Return a True or False instead of ping output. .. code-block:: bash salt '*' network.ping archlinux.org return_boolean=True Set the time to wait for a response in seconds. .. code-block:: bash salt '*' network.ping archlinux.org timeout=3
[ "Performs", "an", "ICMP", "ping", "to", "a", "host" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L63-L104
train
saltstack/salt
salt/modules/network.py
_netstat_linux
def _netstat_linux(): ''' Return netstat information for Linux distros ''' ret = [] cmd = 'netstat -tulpnea' out = __salt__['cmd.run'](cmd) for line in out.splitlines(): comps = line.split() if line.startswith('tcp'): ret.append({ 'proto': comps[0], 'recv-q': comps[1], 'send-q': comps[2], 'local-address': comps[3], 'remote-address': comps[4], 'state': comps[5], 'user': comps[6], 'inode': comps[7], 'program': comps[8]}) if line.startswith('udp'): ret.append({ 'proto': comps[0], 'recv-q': comps[1], 'send-q': comps[2], 'local-address': comps[3], 'remote-address': comps[4], 'user': comps[5], 'inode': comps[6], 'program': comps[7]}) return ret
python
def _netstat_linux(): ''' Return netstat information for Linux distros ''' ret = [] cmd = 'netstat -tulpnea' out = __salt__['cmd.run'](cmd) for line in out.splitlines(): comps = line.split() if line.startswith('tcp'): ret.append({ 'proto': comps[0], 'recv-q': comps[1], 'send-q': comps[2], 'local-address': comps[3], 'remote-address': comps[4], 'state': comps[5], 'user': comps[6], 'inode': comps[7], 'program': comps[8]}) if line.startswith('udp'): ret.append({ 'proto': comps[0], 'recv-q': comps[1], 'send-q': comps[2], 'local-address': comps[3], 'remote-address': comps[4], 'user': comps[5], 'inode': comps[6], 'program': comps[7]}) return ret
[ "def", "_netstat_linux", "(", ")", ":", "ret", "=", "[", "]", "cmd", "=", "'netstat -tulpnea'", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ")", "for", "line", "in", "out", ".", "splitlines", "(", ")", ":", "comps", "=", "line", ".", ...
Return netstat information for Linux distros
[ "Return", "netstat", "information", "for", "Linux", "distros" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L109-L139
train
saltstack/salt
salt/modules/network.py
_ss_linux
def _ss_linux(): ''' Return ss information for Linux distros (netstat is deprecated and may not be available) ''' ret = [] cmd = 'ss -tulpnea' out = __salt__['cmd.run'](cmd) for line in out.splitlines(): comps = line.split() ss_user = 0 ss_inode = 0 ss_program = '' length = len(comps) if line.startswith('tcp') or line.startswith('udp'): i = 6 while i < (length - 1): fields = comps[i].split(":") if fields[0] == "users": users = fields[1].split(",") ss_program = users[0].split("\"")[1] if fields[0] == "uid": ss_user = fields[1] if fields[0] == "ino": ss_inode = fields[1] i += 1 if line.startswith('tcp'): ss_state = comps[1] if ss_state == "ESTAB": ss_state = "ESTABLISHED" ret.append({ 'proto': comps[0], 'recv-q': comps[2], 'send-q': comps[3], 'local-address': comps[4], 'remote-address': comps[5], 'state': ss_state, 'user': ss_user, 'inode': ss_inode, 'program': ss_program}) if line.startswith('udp'): ret.append({ 'proto': comps[0], 'recv-q': comps[2], 'send-q': comps[3], 'local-address': comps[4], 'remote-address': comps[5], 'user': ss_user, 'inode': ss_inode, 'program': ss_program}) return ret
python
def _ss_linux(): ''' Return ss information for Linux distros (netstat is deprecated and may not be available) ''' ret = [] cmd = 'ss -tulpnea' out = __salt__['cmd.run'](cmd) for line in out.splitlines(): comps = line.split() ss_user = 0 ss_inode = 0 ss_program = '' length = len(comps) if line.startswith('tcp') or line.startswith('udp'): i = 6 while i < (length - 1): fields = comps[i].split(":") if fields[0] == "users": users = fields[1].split(",") ss_program = users[0].split("\"")[1] if fields[0] == "uid": ss_user = fields[1] if fields[0] == "ino": ss_inode = fields[1] i += 1 if line.startswith('tcp'): ss_state = comps[1] if ss_state == "ESTAB": ss_state = "ESTABLISHED" ret.append({ 'proto': comps[0], 'recv-q': comps[2], 'send-q': comps[3], 'local-address': comps[4], 'remote-address': comps[5], 'state': ss_state, 'user': ss_user, 'inode': ss_inode, 'program': ss_program}) if line.startswith('udp'): ret.append({ 'proto': comps[0], 'recv-q': comps[2], 'send-q': comps[3], 'local-address': comps[4], 'remote-address': comps[5], 'user': ss_user, 'inode': ss_inode, 'program': ss_program}) return ret
[ "def", "_ss_linux", "(", ")", ":", "ret", "=", "[", "]", "cmd", "=", "'ss -tulpnea'", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ")", "for", "line", "in", "out", ".", "splitlines", "(", ")", ":", "comps", "=", "line", ".", "split", ...
Return ss information for Linux distros (netstat is deprecated and may not be available)
[ "Return", "ss", "information", "for", "Linux", "distros", "(", "netstat", "is", "deprecated", "and", "may", "not", "be", "available", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L142-L196
train
saltstack/salt
salt/modules/network.py
_netinfo_openbsd
def _netinfo_openbsd(): ''' Get process information for network connections using fstat ''' ret = {} _fstat_re = re.compile( r'internet(6)? (?:stream tcp 0x\S+ (\S+)|dgram udp (\S+))' r'(?: [<>=-]+ (\S+))?$' ) out = __salt__['cmd.run']('fstat') for line in out.splitlines(): try: user, cmd, pid, _, details = line.split(None, 4) ipv6, tcp, udp, remote_addr = _fstat_re.match(details).groups() except (ValueError, AttributeError): # Line either doesn't have the right number of columns, or the # regex which looks for address information did not match. Either # way, ignore this line and continue on to the next one. continue if tcp: local_addr = tcp proto = 'tcp{0}'.format('' if ipv6 is None else ipv6) else: local_addr = udp proto = 'udp{0}'.format('' if ipv6 is None else ipv6) if ipv6: # IPv6 addresses have the address part enclosed in brackets (if the # address part is not a wildcard) to distinguish the address from # the port number. Remove them. local_addr = ''.join(x for x in local_addr if x not in '[]') # Normalize to match netstat output local_addr = '.'.join(local_addr.rsplit(':', 1)) if remote_addr is None: remote_addr = '*.*' else: remote_addr = '.'.join(remote_addr.rsplit(':', 1)) ret.setdefault( local_addr, {}).setdefault( remote_addr, {}).setdefault( proto, {}).setdefault( pid, {})['user'] = user ret[local_addr][remote_addr][proto][pid]['cmd'] = cmd return ret
python
def _netinfo_openbsd(): ''' Get process information for network connections using fstat ''' ret = {} _fstat_re = re.compile( r'internet(6)? (?:stream tcp 0x\S+ (\S+)|dgram udp (\S+))' r'(?: [<>=-]+ (\S+))?$' ) out = __salt__['cmd.run']('fstat') for line in out.splitlines(): try: user, cmd, pid, _, details = line.split(None, 4) ipv6, tcp, udp, remote_addr = _fstat_re.match(details).groups() except (ValueError, AttributeError): # Line either doesn't have the right number of columns, or the # regex which looks for address information did not match. Either # way, ignore this line and continue on to the next one. continue if tcp: local_addr = tcp proto = 'tcp{0}'.format('' if ipv6 is None else ipv6) else: local_addr = udp proto = 'udp{0}'.format('' if ipv6 is None else ipv6) if ipv6: # IPv6 addresses have the address part enclosed in brackets (if the # address part is not a wildcard) to distinguish the address from # the port number. Remove them. local_addr = ''.join(x for x in local_addr if x not in '[]') # Normalize to match netstat output local_addr = '.'.join(local_addr.rsplit(':', 1)) if remote_addr is None: remote_addr = '*.*' else: remote_addr = '.'.join(remote_addr.rsplit(':', 1)) ret.setdefault( local_addr, {}).setdefault( remote_addr, {}).setdefault( proto, {}).setdefault( pid, {})['user'] = user ret[local_addr][remote_addr][proto][pid]['cmd'] = cmd return ret
[ "def", "_netinfo_openbsd", "(", ")", ":", "ret", "=", "{", "}", "_fstat_re", "=", "re", ".", "compile", "(", "r'internet(6)? (?:stream tcp 0x\\S+ (\\S+)|dgram udp (\\S+))'", "r'(?: [<>=-]+ (\\S+))?$'", ")", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "'fstat...
Get process information for network connections using fstat
[ "Get", "process", "information", "for", "network", "connections", "using", "fstat" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L199-L243
train
saltstack/salt
salt/modules/network.py
_netinfo_freebsd_netbsd
def _netinfo_freebsd_netbsd(): ''' Get process information for network connections using sockstat ''' ret = {} # NetBSD requires '-n' to disable port-to-service resolution out = __salt__['cmd.run']( 'sockstat -46 {0} | tail -n+2'.format( '-n' if __grains__['kernel'] == 'NetBSD' else '' ), python_shell=True ) for line in out.splitlines(): user, cmd, pid, _, proto, local_addr, remote_addr = line.split() local_addr = '.'.join(local_addr.rsplit(':', 1)) remote_addr = '.'.join(remote_addr.rsplit(':', 1)) ret.setdefault( local_addr, {}).setdefault( remote_addr, {}).setdefault( proto, {}).setdefault( pid, {})['user'] = user ret[local_addr][remote_addr][proto][pid]['cmd'] = cmd return ret
python
def _netinfo_freebsd_netbsd(): ''' Get process information for network connections using sockstat ''' ret = {} # NetBSD requires '-n' to disable port-to-service resolution out = __salt__['cmd.run']( 'sockstat -46 {0} | tail -n+2'.format( '-n' if __grains__['kernel'] == 'NetBSD' else '' ), python_shell=True ) for line in out.splitlines(): user, cmd, pid, _, proto, local_addr, remote_addr = line.split() local_addr = '.'.join(local_addr.rsplit(':', 1)) remote_addr = '.'.join(remote_addr.rsplit(':', 1)) ret.setdefault( local_addr, {}).setdefault( remote_addr, {}).setdefault( proto, {}).setdefault( pid, {})['user'] = user ret[local_addr][remote_addr][proto][pid]['cmd'] = cmd return ret
[ "def", "_netinfo_freebsd_netbsd", "(", ")", ":", "ret", "=", "{", "}", "# NetBSD requires '-n' to disable port-to-service resolution", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "'sockstat -46 {0} | tail -n+2'", ".", "format", "(", "'-n'", "if", "__grains__", ...
Get process information for network connections using sockstat
[ "Get", "process", "information", "for", "network", "connections", "using", "sockstat" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L246-L267
train
saltstack/salt
salt/modules/network.py
_ppid
def _ppid(): ''' Return a dict of pid to ppid mappings ''' ret = {} if __grains__['kernel'] == 'SunOS': cmd = 'ps -a -o pid,ppid | tail +2' else: cmd = 'ps -ax -o pid,ppid | tail -n+2' out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): pid, ppid = line.split() ret[pid] = ppid return ret
python
def _ppid(): ''' Return a dict of pid to ppid mappings ''' ret = {} if __grains__['kernel'] == 'SunOS': cmd = 'ps -a -o pid,ppid | tail +2' else: cmd = 'ps -ax -o pid,ppid | tail -n+2' out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): pid, ppid = line.split() ret[pid] = ppid return ret
[ "def", "_ppid", "(", ")", ":", "ret", "=", "{", "}", "if", "__grains__", "[", "'kernel'", "]", "==", "'SunOS'", ":", "cmd", "=", "'ps -a -o pid,ppid | tail +2'", "else", ":", "cmd", "=", "'ps -ax -o pid,ppid | tail -n+2'", "out", "=", "__salt__", "[", "'cmd....
Return a dict of pid to ppid mappings
[ "Return", "a", "dict", "of", "pid", "to", "ppid", "mappings" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L270-L283
train
saltstack/salt
salt/modules/network.py
_netstat_bsd
def _netstat_bsd(): ''' Return netstat information for BSD flavors ''' ret = [] if __grains__['kernel'] == 'NetBSD': for addr_family in ('inet', 'inet6'): cmd = 'netstat -f {0} -an | tail -n+3'.format(addr_family) out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() entry = { 'proto': comps[0], 'recv-q': comps[1], 'send-q': comps[2], 'local-address': comps[3], 'remote-address': comps[4] } if entry['proto'].startswith('tcp'): entry['state'] = comps[5] ret.append(entry) else: # Lookup TCP connections cmd = 'netstat -p tcp -an | tail -n+3' out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() ret.append({ 'proto': comps[0], 'recv-q': comps[1], 'send-q': comps[2], 'local-address': comps[3], 'remote-address': comps[4], 'state': comps[5]}) # Lookup UDP connections cmd = 'netstat -p udp -an | tail -n+3' out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() ret.append({ 'proto': comps[0], 'recv-q': comps[1], 'send-q': comps[2], 'local-address': comps[3], 'remote-address': comps[4]}) # Add in user and program info ppid = _ppid() if __grains__['kernel'] == 'OpenBSD': netinfo = _netinfo_openbsd() elif __grains__['kernel'] in ('FreeBSD', 'NetBSD'): netinfo = _netinfo_freebsd_netbsd() for idx in range(len(ret)): local = ret[idx]['local-address'] remote = ret[idx]['remote-address'] proto = ret[idx]['proto'] try: # Make a pointer to the info for this connection for easier # reference below ptr = netinfo[local][remote][proto] except KeyError: continue # Get the pid-to-ppid mappings for this connection conn_ppid = dict((x, y) for x, y in six.iteritems(ppid) if x in ptr) try: # Master pid for this connection will be the pid whose ppid isn't # in the subset dict we created above master_pid = next(iter( x for x, y in six.iteritems(conn_ppid) if y not in ptr )) except StopIteration: continue ret[idx]['user'] = ptr[master_pid]['user'] ret[idx]['program'] = '/'.join((master_pid, ptr[master_pid]['cmd'])) return ret
python
def _netstat_bsd(): ''' Return netstat information for BSD flavors ''' ret = [] if __grains__['kernel'] == 'NetBSD': for addr_family in ('inet', 'inet6'): cmd = 'netstat -f {0} -an | tail -n+3'.format(addr_family) out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() entry = { 'proto': comps[0], 'recv-q': comps[1], 'send-q': comps[2], 'local-address': comps[3], 'remote-address': comps[4] } if entry['proto'].startswith('tcp'): entry['state'] = comps[5] ret.append(entry) else: # Lookup TCP connections cmd = 'netstat -p tcp -an | tail -n+3' out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() ret.append({ 'proto': comps[0], 'recv-q': comps[1], 'send-q': comps[2], 'local-address': comps[3], 'remote-address': comps[4], 'state': comps[5]}) # Lookup UDP connections cmd = 'netstat -p udp -an | tail -n+3' out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() ret.append({ 'proto': comps[0], 'recv-q': comps[1], 'send-q': comps[2], 'local-address': comps[3], 'remote-address': comps[4]}) # Add in user and program info ppid = _ppid() if __grains__['kernel'] == 'OpenBSD': netinfo = _netinfo_openbsd() elif __grains__['kernel'] in ('FreeBSD', 'NetBSD'): netinfo = _netinfo_freebsd_netbsd() for idx in range(len(ret)): local = ret[idx]['local-address'] remote = ret[idx]['remote-address'] proto = ret[idx]['proto'] try: # Make a pointer to the info for this connection for easier # reference below ptr = netinfo[local][remote][proto] except KeyError: continue # Get the pid-to-ppid mappings for this connection conn_ppid = dict((x, y) for x, y in six.iteritems(ppid) if x in ptr) try: # Master pid for this connection will be the pid whose ppid isn't # in the subset dict we created above master_pid = next(iter( x for x, y in six.iteritems(conn_ppid) if y not in ptr )) except StopIteration: continue ret[idx]['user'] = ptr[master_pid]['user'] ret[idx]['program'] = '/'.join((master_pid, ptr[master_pid]['cmd'])) return ret
[ "def", "_netstat_bsd", "(", ")", ":", "ret", "=", "[", "]", "if", "__grains__", "[", "'kernel'", "]", "==", "'NetBSD'", ":", "for", "addr_family", "in", "(", "'inet'", ",", "'inet6'", ")", ":", "cmd", "=", "'netstat -f {0} -an | tail -n+3'", ".", "format",...
Return netstat information for BSD flavors
[ "Return", "netstat", "information", "for", "BSD", "flavors" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L286-L360
train
saltstack/salt
salt/modules/network.py
_netstat_sunos
def _netstat_sunos(): ''' Return netstat information for SunOS flavors ''' log.warning('User and program not (yet) supported on SunOS') ret = [] for addr_family in ('inet', 'inet6'): # Lookup TCP connections cmd = 'netstat -f {0} -P tcp -an | tail +5'.format(addr_family) out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() ret.append({ 'proto': 'tcp6' if addr_family == 'inet6' else 'tcp', 'recv-q': comps[5], 'send-q': comps[4], 'local-address': comps[0], 'remote-address': comps[1], 'state': comps[6]}) # Lookup UDP connections cmd = 'netstat -f {0} -P udp -an | tail +5'.format(addr_family) out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() ret.append({ 'proto': 'udp6' if addr_family == 'inet6' else 'udp', 'local-address': comps[0], 'remote-address': comps[1] if len(comps) > 2 else ''}) return ret
python
def _netstat_sunos(): ''' Return netstat information for SunOS flavors ''' log.warning('User and program not (yet) supported on SunOS') ret = [] for addr_family in ('inet', 'inet6'): # Lookup TCP connections cmd = 'netstat -f {0} -P tcp -an | tail +5'.format(addr_family) out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() ret.append({ 'proto': 'tcp6' if addr_family == 'inet6' else 'tcp', 'recv-q': comps[5], 'send-q': comps[4], 'local-address': comps[0], 'remote-address': comps[1], 'state': comps[6]}) # Lookup UDP connections cmd = 'netstat -f {0} -P udp -an | tail +5'.format(addr_family) out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() ret.append({ 'proto': 'udp6' if addr_family == 'inet6' else 'udp', 'local-address': comps[0], 'remote-address': comps[1] if len(comps) > 2 else ''}) return ret
[ "def", "_netstat_sunos", "(", ")", ":", "log", ".", "warning", "(", "'User and program not (yet) supported on SunOS'", ")", "ret", "=", "[", "]", "for", "addr_family", "in", "(", "'inet'", ",", "'inet6'", ")", ":", "# Lookup TCP connections", "cmd", "=", "'netst...
Return netstat information for SunOS flavors
[ "Return", "netstat", "information", "for", "SunOS", "flavors" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L363-L393
train
saltstack/salt
salt/modules/network.py
_netstat_aix
def _netstat_aix(): ''' Return netstat information for SunOS flavors ''' ret = [] ## AIX 6.1 - 7.2, appears to ignore addr_family field contents ## for addr_family in ('inet', 'inet6'): for addr_family in ('inet',): # Lookup connections cmd = 'netstat -n -a -f {0} | tail -n +3'.format(addr_family) out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() if len(comps) < 5: continue proto_seen = None tcp_flag = True if 'tcp' == comps[0] or 'tcp4' == comps[0]: proto_seen = 'tcp' elif 'tcp6' == comps[0]: proto_seen = 'tcp6' elif 'udp' == comps[0] or 'udp4' == comps[0]: proto_seen = 'udp' tcp_flag = False elif 'udp6' == comps[0]: proto_seen = 'udp6' tcp_flag = False if tcp_flag: if len(comps) >= 6: ret.append({ 'proto': proto_seen, 'recv-q': comps[1], 'send-q': comps[2], 'local-address': comps[3], 'remote-address': comps[4], 'state': comps[5]}) else: if len(comps) >= 5: ret.append({ 'proto': proto_seen, 'local-address': comps[3], 'remote-address': comps[4]}) return ret
python
def _netstat_aix(): ''' Return netstat information for SunOS flavors ''' ret = [] ## AIX 6.1 - 7.2, appears to ignore addr_family field contents ## for addr_family in ('inet', 'inet6'): for addr_family in ('inet',): # Lookup connections cmd = 'netstat -n -a -f {0} | tail -n +3'.format(addr_family) out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() if len(comps) < 5: continue proto_seen = None tcp_flag = True if 'tcp' == comps[0] or 'tcp4' == comps[0]: proto_seen = 'tcp' elif 'tcp6' == comps[0]: proto_seen = 'tcp6' elif 'udp' == comps[0] or 'udp4' == comps[0]: proto_seen = 'udp' tcp_flag = False elif 'udp6' == comps[0]: proto_seen = 'udp6' tcp_flag = False if tcp_flag: if len(comps) >= 6: ret.append({ 'proto': proto_seen, 'recv-q': comps[1], 'send-q': comps[2], 'local-address': comps[3], 'remote-address': comps[4], 'state': comps[5]}) else: if len(comps) >= 5: ret.append({ 'proto': proto_seen, 'local-address': comps[3], 'remote-address': comps[4]}) return ret
[ "def", "_netstat_aix", "(", ")", ":", "ret", "=", "[", "]", "## AIX 6.1 - 7.2, appears to ignore addr_family field contents", "## for addr_family in ('inet', 'inet6'):", "for", "addr_family", "in", "(", "'inet'", ",", ")", ":", "# Lookup connections", "cmd", "=", "'netsta...
Return netstat information for SunOS flavors
[ "Return", "netstat", "information", "for", "SunOS", "flavors" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L396-L440
train
saltstack/salt
salt/modules/network.py
_ip_route_linux
def _ip_route_linux(): ''' Return ip routing information for Linux distros (netstat is deprecated and may not be available) ''' # table main closest to old netstat inet output ret = [] cmd = 'ip -4 route show table main' out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() # need to fake similar output to that provided by netstat # to maintain output format if comps[0] == "unreachable": continue if comps[0] == "default": ip_interface = '' if comps[3] == "dev": ip_interface = comps[4] ret.append({ 'addr_family': 'inet', 'destination': '0.0.0.0', 'gateway': comps[2], 'netmask': '0.0.0.0', 'flags': 'UG', 'interface': ip_interface}) else: address_mask = convert_cidr(comps[0]) ip_interface = '' if comps[1] == "dev": ip_interface = comps[2] ret.append({ 'addr_family': 'inet', 'destination': address_mask['network'], 'gateway': '0.0.0.0', 'netmask': address_mask['netmask'], 'flags': 'U', 'interface': ip_interface}) # table all closest to old netstat inet6 output cmd = 'ip -6 route show table all' out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() # need to fake similar output to that provided by netstat # to maintain output format if comps[0] == "unreachable": continue if comps[0] == "default": ip_interface = '' if comps[3] == "dev": ip_interface = comps[4] ret.append({ 'addr_family': 'inet6', 'destination': '::/0', 'gateway': comps[2], 'netmask': '', 'flags': 'UG', 'interface': ip_interface}) elif comps[0] == "local": ip_interface = '' if comps[2] == "dev": ip_interface = comps[3] local_address = comps[1] + "/128" ret.append({ 'addr_family': 'inet6', 'destination': local_address, 'gateway': '::', 'netmask': '', 'flags': 'U', 'interface': ip_interface}) else: address_mask = convert_cidr(comps[0]) ip_interface = '' if comps[1] == "dev": ip_interface = comps[2] ret.append({ 'addr_family': 'inet6', 'destination': comps[0], 'gateway': '::', 'netmask': '', 'flags': 'U', 'interface': ip_interface}) return ret
python
def _ip_route_linux(): ''' Return ip routing information for Linux distros (netstat is deprecated and may not be available) ''' # table main closest to old netstat inet output ret = [] cmd = 'ip -4 route show table main' out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() # need to fake similar output to that provided by netstat # to maintain output format if comps[0] == "unreachable": continue if comps[0] == "default": ip_interface = '' if comps[3] == "dev": ip_interface = comps[4] ret.append({ 'addr_family': 'inet', 'destination': '0.0.0.0', 'gateway': comps[2], 'netmask': '0.0.0.0', 'flags': 'UG', 'interface': ip_interface}) else: address_mask = convert_cidr(comps[0]) ip_interface = '' if comps[1] == "dev": ip_interface = comps[2] ret.append({ 'addr_family': 'inet', 'destination': address_mask['network'], 'gateway': '0.0.0.0', 'netmask': address_mask['netmask'], 'flags': 'U', 'interface': ip_interface}) # table all closest to old netstat inet6 output cmd = 'ip -6 route show table all' out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() # need to fake similar output to that provided by netstat # to maintain output format if comps[0] == "unreachable": continue if comps[0] == "default": ip_interface = '' if comps[3] == "dev": ip_interface = comps[4] ret.append({ 'addr_family': 'inet6', 'destination': '::/0', 'gateway': comps[2], 'netmask': '', 'flags': 'UG', 'interface': ip_interface}) elif comps[0] == "local": ip_interface = '' if comps[2] == "dev": ip_interface = comps[3] local_address = comps[1] + "/128" ret.append({ 'addr_family': 'inet6', 'destination': local_address, 'gateway': '::', 'netmask': '', 'flags': 'U', 'interface': ip_interface}) else: address_mask = convert_cidr(comps[0]) ip_interface = '' if comps[1] == "dev": ip_interface = comps[2] ret.append({ 'addr_family': 'inet6', 'destination': comps[0], 'gateway': '::', 'netmask': '', 'flags': 'U', 'interface': ip_interface}) return ret
[ "def", "_ip_route_linux", "(", ")", ":", "# table main closest to old netstat inet output", "ret", "=", "[", "]", "cmd", "=", "'ip -4 route show table main'", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ",", "python_shell", "=", "True", ")", "for", ...
Return ip routing information for Linux distros (netstat is deprecated and may not be available)
[ "Return", "ip", "routing", "information", "for", "Linux", "distros", "(", "netstat", "is", "deprecated", "and", "may", "not", "be", "available", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L484-L577
train
saltstack/salt
salt/modules/network.py
_netstat_route_freebsd
def _netstat_route_freebsd(): ''' Return netstat routing information for FreeBSD and macOS ''' ret = [] cmd = 'netstat -f inet -rn | tail -n+5' out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() if __grains__['os'] == 'FreeBSD' and int(__grains__.get('osmajorrelease', 0)) < 10: ret.append({ 'addr_family': 'inet', 'destination': comps[0], 'gateway': comps[1], 'netmask': comps[2], 'flags': comps[3], 'interface': comps[5]}) else: ret.append({ 'addr_family': 'inet', 'destination': comps[0], 'gateway': comps[1], 'netmask': '', 'flags': comps[2], 'interface': comps[3]}) cmd = 'netstat -f inet6 -rn | tail -n+5' out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() ret.append({ 'addr_family': 'inet6', 'destination': comps[0], 'gateway': comps[1], 'netmask': '', 'flags': comps[2], 'interface': comps[3]}) return ret
python
def _netstat_route_freebsd(): ''' Return netstat routing information for FreeBSD and macOS ''' ret = [] cmd = 'netstat -f inet -rn | tail -n+5' out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() if __grains__['os'] == 'FreeBSD' and int(__grains__.get('osmajorrelease', 0)) < 10: ret.append({ 'addr_family': 'inet', 'destination': comps[0], 'gateway': comps[1], 'netmask': comps[2], 'flags': comps[3], 'interface': comps[5]}) else: ret.append({ 'addr_family': 'inet', 'destination': comps[0], 'gateway': comps[1], 'netmask': '', 'flags': comps[2], 'interface': comps[3]}) cmd = 'netstat -f inet6 -rn | tail -n+5' out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() ret.append({ 'addr_family': 'inet6', 'destination': comps[0], 'gateway': comps[1], 'netmask': '', 'flags': comps[2], 'interface': comps[3]}) return ret
[ "def", "_netstat_route_freebsd", "(", ")", ":", "ret", "=", "[", "]", "cmd", "=", "'netstat -f inet -rn | tail -n+5'", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ",", "python_shell", "=", "True", ")", "for", "line", "in", "out", ".", "split...
Return netstat routing information for FreeBSD and macOS
[ "Return", "netstat", "routing", "information", "for", "FreeBSD", "and", "macOS" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L580-L616
train
saltstack/salt
salt/modules/network.py
_netstat_route_netbsd
def _netstat_route_netbsd(): ''' Return netstat routing information for NetBSD ''' ret = [] cmd = 'netstat -f inet -rn | tail -n+5' out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() ret.append({ 'addr_family': 'inet', 'destination': comps[0], 'gateway': comps[1], 'netmask': '', 'flags': comps[3], 'interface': comps[6]}) cmd = 'netstat -f inet6 -rn | tail -n+5' out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() ret.append({ 'addr_family': 'inet6', 'destination': comps[0], 'gateway': comps[1], 'netmask': '', 'flags': comps[3], 'interface': comps[6]}) return ret
python
def _netstat_route_netbsd(): ''' Return netstat routing information for NetBSD ''' ret = [] cmd = 'netstat -f inet -rn | tail -n+5' out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() ret.append({ 'addr_family': 'inet', 'destination': comps[0], 'gateway': comps[1], 'netmask': '', 'flags': comps[3], 'interface': comps[6]}) cmd = 'netstat -f inet6 -rn | tail -n+5' out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() ret.append({ 'addr_family': 'inet6', 'destination': comps[0], 'gateway': comps[1], 'netmask': '', 'flags': comps[3], 'interface': comps[6]}) return ret
[ "def", "_netstat_route_netbsd", "(", ")", ":", "ret", "=", "[", "]", "cmd", "=", "'netstat -f inet -rn | tail -n+5'", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ",", "python_shell", "=", "True", ")", "for", "line", "in", "out", ".", "splitl...
Return netstat routing information for NetBSD
[ "Return", "netstat", "routing", "information", "for", "NetBSD" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L619-L646
train
saltstack/salt
salt/modules/network.py
_netstat_route_sunos
def _netstat_route_sunos(): ''' Return netstat routing information for SunOS ''' ret = [] cmd = 'netstat -f inet -rn | tail +5' out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() ret.append({ 'addr_family': 'inet', 'destination': comps[0], 'gateway': comps[1], 'netmask': '', 'flags': comps[2], 'interface': comps[5] if len(comps) >= 6 else ''}) cmd = 'netstat -f inet6 -rn | tail +5' out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() ret.append({ 'addr_family': 'inet6', 'destination': comps[0], 'gateway': comps[1], 'netmask': '', 'flags': comps[2], 'interface': comps[5] if len(comps) >= 6 else ''}) return ret
python
def _netstat_route_sunos(): ''' Return netstat routing information for SunOS ''' ret = [] cmd = 'netstat -f inet -rn | tail +5' out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() ret.append({ 'addr_family': 'inet', 'destination': comps[0], 'gateway': comps[1], 'netmask': '', 'flags': comps[2], 'interface': comps[5] if len(comps) >= 6 else ''}) cmd = 'netstat -f inet6 -rn | tail +5' out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() ret.append({ 'addr_family': 'inet6', 'destination': comps[0], 'gateway': comps[1], 'netmask': '', 'flags': comps[2], 'interface': comps[5] if len(comps) >= 6 else ''}) return ret
[ "def", "_netstat_route_sunos", "(", ")", ":", "ret", "=", "[", "]", "cmd", "=", "'netstat -f inet -rn | tail +5'", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ",", "python_shell", "=", "True", ")", "for", "line", "in", "out", ".", "splitline...
Return netstat routing information for SunOS
[ "Return", "netstat", "routing", "information", "for", "SunOS" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L679-L706
train
saltstack/salt
salt/modules/network.py
netstat
def netstat(): ''' Return information on open ports and states .. note:: On BSD minions, the output contains PID info (where available) for each netstat entry, fetched from sockstat/fstat output. .. versionchanged:: 2014.1.4 Added support for OpenBSD, FreeBSD, and NetBSD .. versionchanged:: 2015.8.0 Added support for SunOS .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' network.netstat ''' if __grains__['kernel'] == 'Linux': if not salt.utils.path.which('netstat'): return _ss_linux() else: return _netstat_linux() elif __grains__['kernel'] in ('OpenBSD', 'FreeBSD', 'NetBSD'): return _netstat_bsd() elif __grains__['kernel'] == 'SunOS': return _netstat_sunos() elif __grains__['kernel'] == 'AIX': return _netstat_aix() raise CommandExecutionError('Not yet supported on this platform')
python
def netstat(): ''' Return information on open ports and states .. note:: On BSD minions, the output contains PID info (where available) for each netstat entry, fetched from sockstat/fstat output. .. versionchanged:: 2014.1.4 Added support for OpenBSD, FreeBSD, and NetBSD .. versionchanged:: 2015.8.0 Added support for SunOS .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' network.netstat ''' if __grains__['kernel'] == 'Linux': if not salt.utils.path.which('netstat'): return _ss_linux() else: return _netstat_linux() elif __grains__['kernel'] in ('OpenBSD', 'FreeBSD', 'NetBSD'): return _netstat_bsd() elif __grains__['kernel'] == 'SunOS': return _netstat_sunos() elif __grains__['kernel'] == 'AIX': return _netstat_aix() raise CommandExecutionError('Not yet supported on this platform')
[ "def", "netstat", "(", ")", ":", "if", "__grains__", "[", "'kernel'", "]", "==", "'Linux'", ":", "if", "not", "salt", ".", "utils", ".", "path", ".", "which", "(", "'netstat'", ")", ":", "return", "_ss_linux", "(", ")", "else", ":", "return", "_netst...
Return information on open ports and states .. note:: On BSD minions, the output contains PID info (where available) for each netstat entry, fetched from sockstat/fstat output. .. versionchanged:: 2014.1.4 Added support for OpenBSD, FreeBSD, and NetBSD .. versionchanged:: 2015.8.0 Added support for SunOS .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' network.netstat
[ "Return", "information", "on", "open", "ports", "and", "states" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L739-L773
train
saltstack/salt
salt/modules/network.py
active_tcp
def active_tcp(): ''' Return a dict containing information on all of the running TCP connections (currently linux and solaris only) .. versionchanged:: 2015.8.4 Added support for SunOS CLI Example: .. code-block:: bash salt '*' network.active_tcp ''' if __grains__['kernel'] == 'Linux': return salt.utils.network.active_tcp() elif __grains__['kernel'] == 'SunOS': # lets use netstat to mimic linux as close as possible ret = {} for connection in _netstat_sunos(): if not connection['proto'].startswith('tcp'): continue if connection['state'] != 'ESTABLISHED': continue ret[len(ret)+1] = { 'local_addr': '.'.join(connection['local-address'].split('.')[:-1]), 'local_port': '.'.join(connection['local-address'].split('.')[-1:]), 'remote_addr': '.'.join(connection['remote-address'].split('.')[:-1]), 'remote_port': '.'.join(connection['remote-address'].split('.')[-1:]) } return ret elif __grains__['kernel'] == 'AIX': # lets use netstat to mimic linux as close as possible ret = {} for connection in _netstat_aix(): if not connection['proto'].startswith('tcp'): continue if connection['state'] != 'ESTABLISHED': continue ret[len(ret)+1] = { 'local_addr': '.'.join(connection['local-address'].split('.')[:-1]), 'local_port': '.'.join(connection['local-address'].split('.')[-1:]), 'remote_addr': '.'.join(connection['remote-address'].split('.')[:-1]), 'remote_port': '.'.join(connection['remote-address'].split('.')[-1:]) } return ret else: return {}
python
def active_tcp(): ''' Return a dict containing information on all of the running TCP connections (currently linux and solaris only) .. versionchanged:: 2015.8.4 Added support for SunOS CLI Example: .. code-block:: bash salt '*' network.active_tcp ''' if __grains__['kernel'] == 'Linux': return salt.utils.network.active_tcp() elif __grains__['kernel'] == 'SunOS': # lets use netstat to mimic linux as close as possible ret = {} for connection in _netstat_sunos(): if not connection['proto'].startswith('tcp'): continue if connection['state'] != 'ESTABLISHED': continue ret[len(ret)+1] = { 'local_addr': '.'.join(connection['local-address'].split('.')[:-1]), 'local_port': '.'.join(connection['local-address'].split('.')[-1:]), 'remote_addr': '.'.join(connection['remote-address'].split('.')[:-1]), 'remote_port': '.'.join(connection['remote-address'].split('.')[-1:]) } return ret elif __grains__['kernel'] == 'AIX': # lets use netstat to mimic linux as close as possible ret = {} for connection in _netstat_aix(): if not connection['proto'].startswith('tcp'): continue if connection['state'] != 'ESTABLISHED': continue ret[len(ret)+1] = { 'local_addr': '.'.join(connection['local-address'].split('.')[:-1]), 'local_port': '.'.join(connection['local-address'].split('.')[-1:]), 'remote_addr': '.'.join(connection['remote-address'].split('.')[:-1]), 'remote_port': '.'.join(connection['remote-address'].split('.')[-1:]) } return ret else: return {}
[ "def", "active_tcp", "(", ")", ":", "if", "__grains__", "[", "'kernel'", "]", "==", "'Linux'", ":", "return", "salt", ".", "utils", ".", "network", ".", "active_tcp", "(", ")", "elif", "__grains__", "[", "'kernel'", "]", "==", "'SunOS'", ":", "# lets use...
Return a dict containing information on all of the running TCP connections (currently linux and solaris only) .. versionchanged:: 2015.8.4 Added support for SunOS CLI Example: .. code-block:: bash salt '*' network.active_tcp
[ "Return", "a", "dict", "containing", "information", "on", "all", "of", "the", "running", "TCP", "connections", "(", "currently", "linux", "and", "solaris", "only", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L776-L823
train
saltstack/salt
salt/modules/network.py
traceroute
def traceroute(host): ''' Performs a traceroute to a 3rd party host .. versionchanged:: 2015.8.0 Added support for SunOS .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' network.traceroute archlinux.org ''' ret = [] if not salt.utils.path.which('traceroute'): log.info('This minion does not have traceroute installed') return ret cmd = 'traceroute {0}'.format(salt.utils.network.sanitize_host(host)) out = __salt__['cmd.run'](cmd) # Parse version of traceroute if salt.utils.platform.is_sunos() or salt.utils.platform.is_aix(): traceroute_version = [0, 0, 0] else: cmd2 = 'traceroute --version' out2 = __salt__['cmd.run'](cmd2) try: # Linux traceroute version looks like: # Modern traceroute for Linux, version 2.0.19, Dec 10 2012 # Darwin and FreeBSD traceroute version looks like: Version 1.4a12+[FreeBSD|Darwin] traceroute_version_raw = re.findall(r'.*[Vv]ersion (\d+)\.([\w\+]+)\.*(\w*)', out2)[0] log.debug('traceroute_version_raw: %s', traceroute_version_raw) traceroute_version = [] for t in traceroute_version_raw: try: traceroute_version.append(int(t)) except ValueError: traceroute_version.append(t) if len(traceroute_version) < 3: traceroute_version.append(0) log.debug('traceroute_version: %s', traceroute_version) except IndexError: traceroute_version = [0, 0, 0] for line in out.splitlines(): if ' ' not in line: continue if line.startswith('traceroute'): continue if salt.utils.platform.is_aix(): if line.startswith('trying to get source for'): continue if line.startswith('source should be'): continue if line.startswith('outgoing MTU'): continue if line.startswith('fragmentation required'): continue if 'Darwin' in six.text_type(traceroute_version[1]) or \ 'FreeBSD' in six.text_type(traceroute_version[1]) or \ __grains__['kernel'] in ('SunOS', 'AIX'): try: traceline = re.findall(r'\s*(\d*)\s+(.*)\s+\((.*)\)\s+(.*)$', line)[0] except IndexError: traceline = re.findall(r'\s*(\d*)\s+(\*\s+\*\s+\*)', line)[0] log.debug('traceline: %s', traceline) delays = re.findall(r'(\d+\.\d+)\s*ms', six.text_type(traceline)) try: if traceline[1] == '* * *': result = { 'count': traceline[0], 'hostname': '*' } else: result = { 'count': traceline[0], 'hostname': traceline[1], 'ip': traceline[2], } for idx in range(0, len(delays)): result['ms{0}'.format(idx + 1)] = delays[idx] except IndexError: result = {} elif (traceroute_version[0] >= 2 and traceroute_version[2] >= 14 or traceroute_version[0] >= 2 and traceroute_version[1] > 0): comps = line.split(' ') if comps[1] == '* * *': result = { 'count': int(comps[0]), 'hostname': '*'} else: result = { 'count': int(comps[0]), 'hostname': comps[1].split()[0], 'ip': comps[1].split()[1].strip('()'), 'ms1': float(comps[2].split()[0]), 'ms2': float(comps[3].split()[0]), 'ms3': float(comps[4].split()[0])} else: comps = line.split() result = { 'count': comps[0], 'hostname': comps[1], 'ip': comps[2], 'ms1': comps[4], 'ms2': comps[6], 'ms3': comps[8], 'ping1': comps[3], 'ping2': comps[5], 'ping3': comps[7]} ret.append(result) return ret
python
def traceroute(host): ''' Performs a traceroute to a 3rd party host .. versionchanged:: 2015.8.0 Added support for SunOS .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' network.traceroute archlinux.org ''' ret = [] if not salt.utils.path.which('traceroute'): log.info('This minion does not have traceroute installed') return ret cmd = 'traceroute {0}'.format(salt.utils.network.sanitize_host(host)) out = __salt__['cmd.run'](cmd) # Parse version of traceroute if salt.utils.platform.is_sunos() or salt.utils.platform.is_aix(): traceroute_version = [0, 0, 0] else: cmd2 = 'traceroute --version' out2 = __salt__['cmd.run'](cmd2) try: # Linux traceroute version looks like: # Modern traceroute for Linux, version 2.0.19, Dec 10 2012 # Darwin and FreeBSD traceroute version looks like: Version 1.4a12+[FreeBSD|Darwin] traceroute_version_raw = re.findall(r'.*[Vv]ersion (\d+)\.([\w\+]+)\.*(\w*)', out2)[0] log.debug('traceroute_version_raw: %s', traceroute_version_raw) traceroute_version = [] for t in traceroute_version_raw: try: traceroute_version.append(int(t)) except ValueError: traceroute_version.append(t) if len(traceroute_version) < 3: traceroute_version.append(0) log.debug('traceroute_version: %s', traceroute_version) except IndexError: traceroute_version = [0, 0, 0] for line in out.splitlines(): if ' ' not in line: continue if line.startswith('traceroute'): continue if salt.utils.platform.is_aix(): if line.startswith('trying to get source for'): continue if line.startswith('source should be'): continue if line.startswith('outgoing MTU'): continue if line.startswith('fragmentation required'): continue if 'Darwin' in six.text_type(traceroute_version[1]) or \ 'FreeBSD' in six.text_type(traceroute_version[1]) or \ __grains__['kernel'] in ('SunOS', 'AIX'): try: traceline = re.findall(r'\s*(\d*)\s+(.*)\s+\((.*)\)\s+(.*)$', line)[0] except IndexError: traceline = re.findall(r'\s*(\d*)\s+(\*\s+\*\s+\*)', line)[0] log.debug('traceline: %s', traceline) delays = re.findall(r'(\d+\.\d+)\s*ms', six.text_type(traceline)) try: if traceline[1] == '* * *': result = { 'count': traceline[0], 'hostname': '*' } else: result = { 'count': traceline[0], 'hostname': traceline[1], 'ip': traceline[2], } for idx in range(0, len(delays)): result['ms{0}'.format(idx + 1)] = delays[idx] except IndexError: result = {} elif (traceroute_version[0] >= 2 and traceroute_version[2] >= 14 or traceroute_version[0] >= 2 and traceroute_version[1] > 0): comps = line.split(' ') if comps[1] == '* * *': result = { 'count': int(comps[0]), 'hostname': '*'} else: result = { 'count': int(comps[0]), 'hostname': comps[1].split()[0], 'ip': comps[1].split()[1].strip('()'), 'ms1': float(comps[2].split()[0]), 'ms2': float(comps[3].split()[0]), 'ms3': float(comps[4].split()[0])} else: comps = line.split() result = { 'count': comps[0], 'hostname': comps[1], 'ip': comps[2], 'ms1': comps[4], 'ms2': comps[6], 'ms3': comps[8], 'ping1': comps[3], 'ping2': comps[5], 'ping3': comps[7]} ret.append(result) return ret
[ "def", "traceroute", "(", "host", ")", ":", "ret", "=", "[", "]", "if", "not", "salt", ".", "utils", ".", "path", ".", "which", "(", "'traceroute'", ")", ":", "log", ".", "info", "(", "'This minion does not have traceroute installed'", ")", "return", "ret"...
Performs a traceroute to a 3rd party host .. versionchanged:: 2015.8.0 Added support for SunOS .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' network.traceroute archlinux.org
[ "Performs", "a", "traceroute", "to", "a", "3rd", "party", "host" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L826-L956
train
saltstack/salt
salt/modules/network.py
dig
def dig(host): ''' Performs a DNS lookup with dig CLI Example: .. code-block:: bash salt '*' network.dig archlinux.org ''' cmd = 'dig {0}'.format(salt.utils.network.sanitize_host(host)) return __salt__['cmd.run'](cmd)
python
def dig(host): ''' Performs a DNS lookup with dig CLI Example: .. code-block:: bash salt '*' network.dig archlinux.org ''' cmd = 'dig {0}'.format(salt.utils.network.sanitize_host(host)) return __salt__['cmd.run'](cmd)
[ "def", "dig", "(", "host", ")", ":", "cmd", "=", "'dig {0}'", ".", "format", "(", "salt", ".", "utils", ".", "network", ".", "sanitize_host", "(", "host", ")", ")", "return", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ")" ]
Performs a DNS lookup with dig CLI Example: .. code-block:: bash salt '*' network.dig archlinux.org
[ "Performs", "a", "DNS", "lookup", "with", "dig" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L960-L971
train
saltstack/salt
salt/modules/network.py
arp
def arp(): ''' Return the arp table from the minion .. versionchanged:: 2015.8.0 Added support for SunOS CLI Example: .. code-block:: bash salt '*' network.arp ''' ret = {} out = __salt__['cmd.run']('arp -an') for line in out.splitlines(): comps = line.split() if len(comps) < 4: continue if __grains__['kernel'] == 'SunOS': if ':' not in comps[-1]: continue ret[comps[-1]] = comps[1] elif __grains__['kernel'] == 'OpenBSD': if comps[0] == 'Host' or comps[1] == '(incomplete)': continue ret[comps[1]] = comps[0] elif __grains__['kernel'] == 'AIX': if comps[0] in ('bucket', 'There'): continue ret[comps[3]] = comps[1].strip('(').strip(')') else: ret[comps[3]] = comps[1].strip('(').strip(')') return ret
python
def arp(): ''' Return the arp table from the minion .. versionchanged:: 2015.8.0 Added support for SunOS CLI Example: .. code-block:: bash salt '*' network.arp ''' ret = {} out = __salt__['cmd.run']('arp -an') for line in out.splitlines(): comps = line.split() if len(comps) < 4: continue if __grains__['kernel'] == 'SunOS': if ':' not in comps[-1]: continue ret[comps[-1]] = comps[1] elif __grains__['kernel'] == 'OpenBSD': if comps[0] == 'Host' or comps[1] == '(incomplete)': continue ret[comps[1]] = comps[0] elif __grains__['kernel'] == 'AIX': if comps[0] in ('bucket', 'There'): continue ret[comps[3]] = comps[1].strip('(').strip(')') else: ret[comps[3]] = comps[1].strip('(').strip(')') return ret
[ "def", "arp", "(", ")", ":", "ret", "=", "{", "}", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "'arp -an'", ")", "for", "line", "in", "out", ".", "splitlines", "(", ")", ":", "comps", "=", "line", ".", "split", "(", ")", "if", "len", "(...
Return the arp table from the minion .. versionchanged:: 2015.8.0 Added support for SunOS CLI Example: .. code-block:: bash salt '*' network.arp
[ "Return", "the", "arp", "table", "from", "the", "minion" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L975-L1009
train
saltstack/salt
salt/modules/network.py
convert_cidr
def convert_cidr(cidr): ''' returns the network address, subnet mask and broadcast address of a cidr address .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' network.convert_cidr 172.31.0.0/16 ''' ret = {'network': None, 'netmask': None, 'broadcast': None} cidr = calc_net(cidr) network_info = ipaddress.ip_network(cidr) ret['network'] = six.text_type(network_info.network_address) ret['netmask'] = six.text_type(network_info.netmask) ret['broadcast'] = six.text_type(network_info.broadcast_address) return ret
python
def convert_cidr(cidr): ''' returns the network address, subnet mask and broadcast address of a cidr address .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' network.convert_cidr 172.31.0.0/16 ''' ret = {'network': None, 'netmask': None, 'broadcast': None} cidr = calc_net(cidr) network_info = ipaddress.ip_network(cidr) ret['network'] = six.text_type(network_info.network_address) ret['netmask'] = six.text_type(network_info.netmask) ret['broadcast'] = six.text_type(network_info.broadcast_address) return ret
[ "def", "convert_cidr", "(", "cidr", ")", ":", "ret", "=", "{", "'network'", ":", "None", ",", "'netmask'", ":", "None", ",", "'broadcast'", ":", "None", "}", "cidr", "=", "calc_net", "(", "cidr", ")", "network_info", "=", "ipaddress", ".", "ip_network", ...
returns the network address, subnet mask and broadcast address of a cidr address .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' network.convert_cidr 172.31.0.0/16
[ "returns", "the", "network", "address", "subnet", "mask", "and", "broadcast", "address", "of", "a", "cidr", "address" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L1125-L1145
train
saltstack/salt
salt/modules/network.py
mod_hostname
def mod_hostname(hostname): ''' Modify hostname .. versionchanged:: 2015.8.0 Added support for SunOS (Solaris 10, Illumos, SmartOS) CLI Example: .. code-block:: bash salt '*' network.mod_hostname master.saltstack.com ''' # # SunOS tested on SmartOS and OmniOS (Solaris 10 compatible) # Oracle Solaris 11 uses smf, currently not supported # # /etc/nodename is the hostname only, not fqdn # /etc/defaultdomain is the domain # /etc/hosts should have both fqdn and hostname entries # if hostname is None: return False hostname_cmd = salt.utils.path.which('hostnamectl') or salt.utils.path.which('hostname') if salt.utils.platform.is_sunos(): uname_cmd = '/usr/bin/uname' if salt.utils.platform.is_smartos() else salt.utils.path.which('uname') check_hostname_cmd = salt.utils.path.which('check-hostname') # Grab the old hostname so we know which hostname to change and then # change the hostname using the hostname command if hostname_cmd.endswith('hostnamectl'): result = __salt__['cmd.run_all']('{0} status'.format(hostname_cmd)) if 0 == result['retcode']: out = result['stdout'] for line in out.splitlines(): line = line.split(':') if 'Static hostname' in line[0]: o_hostname = line[1].strip() else: log.debug('%s was unable to get hostname', hostname_cmd) o_hostname = __salt__['network.get_hostname']() elif not salt.utils.platform.is_sunos(): # don't run hostname -f because -f is not supported on all platforms o_hostname = socket.getfqdn() else: # output: Hostname core OK: fully qualified as core.acheron.be o_hostname = __salt__['cmd.run'](check_hostname_cmd).split(' ')[-1] if hostname_cmd.endswith('hostnamectl'): result = __salt__['cmd.run_all']('{0} set-hostname {1}'.format( hostname_cmd, hostname, )) if result['retcode'] != 0: log.debug('%s was unable to set hostname. Error: %s', hostname_cmd, result['stderr']) return False elif not salt.utils.platform.is_sunos(): __salt__['cmd.run']('{0} {1}'.format(hostname_cmd, hostname)) else: __salt__['cmd.run']('{0} -S {1}'.format(uname_cmd, hostname.split('.')[0])) # Modify the /etc/hosts file to replace the old hostname with the # new hostname with salt.utils.files.fopen('/etc/hosts', 'r') as fp_: host_c = [salt.utils.stringutils.to_unicode(_l) for _l in fp_.readlines()] with salt.utils.files.fopen('/etc/hosts', 'w') as fh_: for host in host_c: host = host.split() try: host[host.index(o_hostname)] = hostname if salt.utils.platform.is_sunos(): # also set a copy of the hostname host[host.index(o_hostname.split('.')[0])] = hostname.split('.')[0] except ValueError: pass fh_.write(salt.utils.stringutils.to_str('\t'.join(host) + '\n')) # Modify the /etc/sysconfig/network configuration file to set the # new hostname if __grains__['os_family'] == 'RedHat': with salt.utils.files.fopen('/etc/sysconfig/network', 'r') as fp_: network_c = [salt.utils.stringutils.to_unicode(_l) for _l in fp_.readlines()] with salt.utils.files.fopen('/etc/sysconfig/network', 'w') as fh_: for net in network_c: if net.startswith('HOSTNAME'): old_hostname = net.split('=', 1)[1].rstrip() quote_type = salt.utils.stringutils.is_quoted(old_hostname) fh_.write(salt.utils.stringutils.to_str( 'HOSTNAME={1}{0}{1}\n'.format( salt.utils.stringutils.dequote(hostname), quote_type))) else: fh_.write(salt.utils.stringutils.to_str(net)) elif __grains__['os_family'] in ('Debian', 'NILinuxRT'): with salt.utils.files.fopen('/etc/hostname', 'w') as fh_: fh_.write(salt.utils.stringutils.to_str(hostname + '\n')) if __grains__['lsb_distrib_id'] == 'nilrt': str_hostname = salt.utils.stringutils.to_str(hostname) nirtcfg_cmd = '/usr/local/natinst/bin/nirtcfg' nirtcfg_cmd += ' --set section=SystemSettings,token=\'Host_Name\',value=\'{0}\''.format(str_hostname) if __salt__['cmd.run_all'](nirtcfg_cmd)['retcode'] != 0: raise CommandExecutionError('Couldn\'t set hostname to: {0}\n'.format(str_hostname)) elif __grains__['os_family'] == 'OpenBSD': with salt.utils.files.fopen('/etc/myname', 'w') as fh_: fh_.write(salt.utils.stringutils.to_str(hostname + '\n')) # Update /etc/nodename and /etc/defaultdomain on SunOS if salt.utils.platform.is_sunos(): with salt.utils.files.fopen('/etc/nodename', 'w') as fh_: fh_.write(salt.utils.stringutils.to_str( hostname.split('.')[0] + '\n') ) with salt.utils.files.fopen('/etc/defaultdomain', 'w') as fh_: fh_.write(salt.utils.stringutils.to_str( ".".join(hostname.split('.')[1:]) + '\n') ) return True
python
def mod_hostname(hostname): ''' Modify hostname .. versionchanged:: 2015.8.0 Added support for SunOS (Solaris 10, Illumos, SmartOS) CLI Example: .. code-block:: bash salt '*' network.mod_hostname master.saltstack.com ''' # # SunOS tested on SmartOS and OmniOS (Solaris 10 compatible) # Oracle Solaris 11 uses smf, currently not supported # # /etc/nodename is the hostname only, not fqdn # /etc/defaultdomain is the domain # /etc/hosts should have both fqdn and hostname entries # if hostname is None: return False hostname_cmd = salt.utils.path.which('hostnamectl') or salt.utils.path.which('hostname') if salt.utils.platform.is_sunos(): uname_cmd = '/usr/bin/uname' if salt.utils.platform.is_smartos() else salt.utils.path.which('uname') check_hostname_cmd = salt.utils.path.which('check-hostname') # Grab the old hostname so we know which hostname to change and then # change the hostname using the hostname command if hostname_cmd.endswith('hostnamectl'): result = __salt__['cmd.run_all']('{0} status'.format(hostname_cmd)) if 0 == result['retcode']: out = result['stdout'] for line in out.splitlines(): line = line.split(':') if 'Static hostname' in line[0]: o_hostname = line[1].strip() else: log.debug('%s was unable to get hostname', hostname_cmd) o_hostname = __salt__['network.get_hostname']() elif not salt.utils.platform.is_sunos(): # don't run hostname -f because -f is not supported on all platforms o_hostname = socket.getfqdn() else: # output: Hostname core OK: fully qualified as core.acheron.be o_hostname = __salt__['cmd.run'](check_hostname_cmd).split(' ')[-1] if hostname_cmd.endswith('hostnamectl'): result = __salt__['cmd.run_all']('{0} set-hostname {1}'.format( hostname_cmd, hostname, )) if result['retcode'] != 0: log.debug('%s was unable to set hostname. Error: %s', hostname_cmd, result['stderr']) return False elif not salt.utils.platform.is_sunos(): __salt__['cmd.run']('{0} {1}'.format(hostname_cmd, hostname)) else: __salt__['cmd.run']('{0} -S {1}'.format(uname_cmd, hostname.split('.')[0])) # Modify the /etc/hosts file to replace the old hostname with the # new hostname with salt.utils.files.fopen('/etc/hosts', 'r') as fp_: host_c = [salt.utils.stringutils.to_unicode(_l) for _l in fp_.readlines()] with salt.utils.files.fopen('/etc/hosts', 'w') as fh_: for host in host_c: host = host.split() try: host[host.index(o_hostname)] = hostname if salt.utils.platform.is_sunos(): # also set a copy of the hostname host[host.index(o_hostname.split('.')[0])] = hostname.split('.')[0] except ValueError: pass fh_.write(salt.utils.stringutils.to_str('\t'.join(host) + '\n')) # Modify the /etc/sysconfig/network configuration file to set the # new hostname if __grains__['os_family'] == 'RedHat': with salt.utils.files.fopen('/etc/sysconfig/network', 'r') as fp_: network_c = [salt.utils.stringutils.to_unicode(_l) for _l in fp_.readlines()] with salt.utils.files.fopen('/etc/sysconfig/network', 'w') as fh_: for net in network_c: if net.startswith('HOSTNAME'): old_hostname = net.split('=', 1)[1].rstrip() quote_type = salt.utils.stringutils.is_quoted(old_hostname) fh_.write(salt.utils.stringutils.to_str( 'HOSTNAME={1}{0}{1}\n'.format( salt.utils.stringutils.dequote(hostname), quote_type))) else: fh_.write(salt.utils.stringutils.to_str(net)) elif __grains__['os_family'] in ('Debian', 'NILinuxRT'): with salt.utils.files.fopen('/etc/hostname', 'w') as fh_: fh_.write(salt.utils.stringutils.to_str(hostname + '\n')) if __grains__['lsb_distrib_id'] == 'nilrt': str_hostname = salt.utils.stringutils.to_str(hostname) nirtcfg_cmd = '/usr/local/natinst/bin/nirtcfg' nirtcfg_cmd += ' --set section=SystemSettings,token=\'Host_Name\',value=\'{0}\''.format(str_hostname) if __salt__['cmd.run_all'](nirtcfg_cmd)['retcode'] != 0: raise CommandExecutionError('Couldn\'t set hostname to: {0}\n'.format(str_hostname)) elif __grains__['os_family'] == 'OpenBSD': with salt.utils.files.fopen('/etc/myname', 'w') as fh_: fh_.write(salt.utils.stringutils.to_str(hostname + '\n')) # Update /etc/nodename and /etc/defaultdomain on SunOS if salt.utils.platform.is_sunos(): with salt.utils.files.fopen('/etc/nodename', 'w') as fh_: fh_.write(salt.utils.stringutils.to_str( hostname.split('.')[0] + '\n') ) with salt.utils.files.fopen('/etc/defaultdomain', 'w') as fh_: fh_.write(salt.utils.stringutils.to_str( ".".join(hostname.split('.')[1:]) + '\n') ) return True
[ "def", "mod_hostname", "(", "hostname", ")", ":", "#", "# SunOS tested on SmartOS and OmniOS (Solaris 10 compatible)", "# Oracle Solaris 11 uses smf, currently not supported", "#", "# /etc/nodename is the hostname only, not fqdn", "# /etc/defaultdomain is the domain", "# /etc/hosts should ha...
Modify hostname .. versionchanged:: 2015.8.0 Added support for SunOS (Solaris 10, Illumos, SmartOS) CLI Example: .. code-block:: bash salt '*' network.mod_hostname master.saltstack.com
[ "Modify", "hostname" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L1250-L1376
train
saltstack/salt
salt/modules/network.py
_get_bufsize_linux
def _get_bufsize_linux(iface): ''' Return network interface buffer information using ethtool ''' ret = {'result': False} cmd = '/sbin/ethtool -g {0}'.format(iface) out = __salt__['cmd.run'](cmd) pat = re.compile(r'^(.+):\s+(\d+)$') suffix = 'max-' for line in out.splitlines(): res = pat.match(line) if res: ret[res.group(1).lower().replace(' ', '-') + suffix] = int(res.group(2)) ret['result'] = True elif line.endswith('maximums:'): suffix = '-max' elif line.endswith('settings:'): suffix = '' if not ret['result']: parts = out.split() # remove shell cmd prefix from msg if parts[0].endswith('sh:'): out = ' '.join(parts[1:]) ret['comment'] = out return ret
python
def _get_bufsize_linux(iface): ''' Return network interface buffer information using ethtool ''' ret = {'result': False} cmd = '/sbin/ethtool -g {0}'.format(iface) out = __salt__['cmd.run'](cmd) pat = re.compile(r'^(.+):\s+(\d+)$') suffix = 'max-' for line in out.splitlines(): res = pat.match(line) if res: ret[res.group(1).lower().replace(' ', '-') + suffix] = int(res.group(2)) ret['result'] = True elif line.endswith('maximums:'): suffix = '-max' elif line.endswith('settings:'): suffix = '' if not ret['result']: parts = out.split() # remove shell cmd prefix from msg if parts[0].endswith('sh:'): out = ' '.join(parts[1:]) ret['comment'] = out return ret
[ "def", "_get_bufsize_linux", "(", "iface", ")", ":", "ret", "=", "{", "'result'", ":", "False", "}", "cmd", "=", "'/sbin/ethtool -g {0}'", ".", "format", "(", "iface", ")", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ")", "pat", "=", "re...
Return network interface buffer information using ethtool
[ "Return", "network", "interface", "buffer", "information", "using", "ethtool" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L1524-L1549
train
saltstack/salt
salt/modules/network.py
_mod_bufsize_linux
def _mod_bufsize_linux(iface, *args, **kwargs): ''' Modify network interface buffer sizes using ethtool ''' ret = {'result': False, 'comment': 'Requires rx=<val> tx==<val> rx-mini=<val> and/or rx-jumbo=<val>'} cmd = '/sbin/ethtool -G ' + iface if not kwargs: return ret if args: ret['comment'] = 'Unknown arguments: ' + ' '.join([six.text_type(item) for item in args]) return ret eargs = '' for kw in ['rx', 'tx', 'rx-mini', 'rx-jumbo']: value = kwargs.get(kw) if value is not None: eargs += ' ' + kw + ' ' + six.text_type(value) if not eargs: return ret cmd += eargs out = __salt__['cmd.run'](cmd) if out: ret['comment'] = out else: ret['comment'] = eargs.strip() ret['result'] = True return ret
python
def _mod_bufsize_linux(iface, *args, **kwargs): ''' Modify network interface buffer sizes using ethtool ''' ret = {'result': False, 'comment': 'Requires rx=<val> tx==<val> rx-mini=<val> and/or rx-jumbo=<val>'} cmd = '/sbin/ethtool -G ' + iface if not kwargs: return ret if args: ret['comment'] = 'Unknown arguments: ' + ' '.join([six.text_type(item) for item in args]) return ret eargs = '' for kw in ['rx', 'tx', 'rx-mini', 'rx-jumbo']: value = kwargs.get(kw) if value is not None: eargs += ' ' + kw + ' ' + six.text_type(value) if not eargs: return ret cmd += eargs out = __salt__['cmd.run'](cmd) if out: ret['comment'] = out else: ret['comment'] = eargs.strip() ret['result'] = True return ret
[ "def", "_mod_bufsize_linux", "(", "iface", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'result'", ":", "False", ",", "'comment'", ":", "'Requires rx=<val> tx==<val> rx-mini=<val> and/or rx-jumbo=<val>'", "}", "cmd", "=", "'/sbin/ethtool ...
Modify network interface buffer sizes using ethtool
[ "Modify", "network", "interface", "buffer", "sizes", "using", "ethtool" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L1569-L1596
train
saltstack/salt
salt/modules/network.py
mod_bufsize
def mod_bufsize(iface, *args, **kwargs): ''' Modify network interface buffers (currently linux only) CLI Example: .. code-block:: bash salt '*' network.mod_bufsize tx=<val> rx=<val> rx-mini=<val> rx-jumbo=<val> ''' if __grains__['kernel'] == 'Linux': if os.path.exists('/sbin/ethtool'): return _mod_bufsize_linux(iface, *args, **kwargs) return False
python
def mod_bufsize(iface, *args, **kwargs): ''' Modify network interface buffers (currently linux only) CLI Example: .. code-block:: bash salt '*' network.mod_bufsize tx=<val> rx=<val> rx-mini=<val> rx-jumbo=<val> ''' if __grains__['kernel'] == 'Linux': if os.path.exists('/sbin/ethtool'): return _mod_bufsize_linux(iface, *args, **kwargs) return False
[ "def", "mod_bufsize", "(", "iface", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "__grains__", "[", "'kernel'", "]", "==", "'Linux'", ":", "if", "os", ".", "path", ".", "exists", "(", "'/sbin/ethtool'", ")", ":", "return", "_mod_bufsize_l...
Modify network interface buffers (currently linux only) CLI Example: .. code-block:: bash salt '*' network.mod_bufsize tx=<val> rx=<val> rx-mini=<val> rx-jumbo=<val>
[ "Modify", "network", "interface", "buffers", "(", "currently", "linux", "only", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L1599-L1613
train
saltstack/salt
salt/modules/network.py
routes
def routes(family=None): ''' Return currently configured routes from routing table .. versionchanged:: 2015.8.0 Added support for SunOS (Solaris 10, Illumos, SmartOS) .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' network.routes ''' if family != 'inet' and family != 'inet6' and family is not None: raise CommandExecutionError('Invalid address family {0}'.format(family)) if __grains__['kernel'] == 'Linux': if not salt.utils.path.which('netstat'): routes_ = _ip_route_linux() else: routes_ = _netstat_route_linux() elif __grains__['kernel'] == 'SunOS': routes_ = _netstat_route_sunos() elif __grains__['os'] in ['FreeBSD', 'MacOS', 'Darwin']: routes_ = _netstat_route_freebsd() elif __grains__['os'] in ['NetBSD']: routes_ = _netstat_route_netbsd() elif __grains__['os'] in ['OpenBSD']: routes_ = _netstat_route_openbsd() elif __grains__['os'] in ['AIX']: routes_ = _netstat_route_aix() else: raise CommandExecutionError('Not yet supported on this platform') if not family: return routes_ else: ret = [route for route in routes_ if route['addr_family'] == family] return ret
python
def routes(family=None): ''' Return currently configured routes from routing table .. versionchanged:: 2015.8.0 Added support for SunOS (Solaris 10, Illumos, SmartOS) .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' network.routes ''' if family != 'inet' and family != 'inet6' and family is not None: raise CommandExecutionError('Invalid address family {0}'.format(family)) if __grains__['kernel'] == 'Linux': if not salt.utils.path.which('netstat'): routes_ = _ip_route_linux() else: routes_ = _netstat_route_linux() elif __grains__['kernel'] == 'SunOS': routes_ = _netstat_route_sunos() elif __grains__['os'] in ['FreeBSD', 'MacOS', 'Darwin']: routes_ = _netstat_route_freebsd() elif __grains__['os'] in ['NetBSD']: routes_ = _netstat_route_netbsd() elif __grains__['os'] in ['OpenBSD']: routes_ = _netstat_route_openbsd() elif __grains__['os'] in ['AIX']: routes_ = _netstat_route_aix() else: raise CommandExecutionError('Not yet supported on this platform') if not family: return routes_ else: ret = [route for route in routes_ if route['addr_family'] == family] return ret
[ "def", "routes", "(", "family", "=", "None", ")", ":", "if", "family", "!=", "'inet'", "and", "family", "!=", "'inet6'", "and", "family", "is", "not", "None", ":", "raise", "CommandExecutionError", "(", "'Invalid address family {0}'", ".", "format", "(", "fa...
Return currently configured routes from routing table .. versionchanged:: 2015.8.0 Added support for SunOS (Solaris 10, Illumos, SmartOS) .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' network.routes
[ "Return", "currently", "configured", "routes", "from", "routing", "table" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L1616-L1657
train
saltstack/salt
salt/modules/network.py
default_route
def default_route(family=None): ''' Return default route(s) from routing table .. versionchanged:: 2015.8.0 Added support for SunOS (Solaris 10, Illumos, SmartOS) .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' network.default_route ''' if family != 'inet' and family != 'inet6' and family is not None: raise CommandExecutionError('Invalid address family {0}'.format(family)) _routes = routes() default_route = {} if __grains__['kernel'] == 'Linux': default_route['inet'] = ['0.0.0.0', 'default'] default_route['inet6'] = ['::/0', 'default'] elif __grains__['os'] in ['FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS', 'Darwin'] or \ __grains__['kernel'] in ('SunOS', 'AIX'): default_route['inet'] = ['default'] default_route['inet6'] = ['default'] else: raise CommandExecutionError('Not yet supported on this platform') ret = [] for route in _routes: if family: if route['destination'] in default_route[family]: if __grains__['kernel'] == 'SunOS' and route['addr_family'] != family: continue ret.append(route) else: if route['destination'] in default_route['inet'] or \ route['destination'] in default_route['inet6']: ret.append(route) return ret
python
def default_route(family=None): ''' Return default route(s) from routing table .. versionchanged:: 2015.8.0 Added support for SunOS (Solaris 10, Illumos, SmartOS) .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' network.default_route ''' if family != 'inet' and family != 'inet6' and family is not None: raise CommandExecutionError('Invalid address family {0}'.format(family)) _routes = routes() default_route = {} if __grains__['kernel'] == 'Linux': default_route['inet'] = ['0.0.0.0', 'default'] default_route['inet6'] = ['::/0', 'default'] elif __grains__['os'] in ['FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS', 'Darwin'] or \ __grains__['kernel'] in ('SunOS', 'AIX'): default_route['inet'] = ['default'] default_route['inet6'] = ['default'] else: raise CommandExecutionError('Not yet supported on this platform') ret = [] for route in _routes: if family: if route['destination'] in default_route[family]: if __grains__['kernel'] == 'SunOS' and route['addr_family'] != family: continue ret.append(route) else: if route['destination'] in default_route['inet'] or \ route['destination'] in default_route['inet6']: ret.append(route) return ret
[ "def", "default_route", "(", "family", "=", "None", ")", ":", "if", "family", "!=", "'inet'", "and", "family", "!=", "'inet6'", "and", "family", "is", "not", "None", ":", "raise", "CommandExecutionError", "(", "'Invalid address family {0}'", ".", "format", "("...
Return default route(s) from routing table .. versionchanged:: 2015.8.0 Added support for SunOS (Solaris 10, Illumos, SmartOS) .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' network.default_route
[ "Return", "default", "route", "(", "s", ")", "from", "routing", "table" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L1660-L1704
train
saltstack/salt
salt/modules/network.py
get_route
def get_route(ip): ''' Return routing information for given destination ip .. versionadded:: 2015.5.3 .. versionchanged:: 2015.8.0 Added support for SunOS (Solaris 10, Illumos, SmartOS) Added support for OpenBSD .. versionchanged:: 2016.11.4 Added support for AIX CLI Example:: salt '*' network.get_route 10.10.10.10 ''' if __grains__['kernel'] == 'Linux': cmd = 'ip route get {0}'.format(ip) out = __salt__['cmd.run'](cmd, python_shell=True) regexp = re.compile(r'(via\s+(?P<gateway>[\w\.:]+))?\s+dev\s+(?P<interface>[\w\.\:\-]+)\s+.*src\s+(?P<source>[\w\.:]+)') m = regexp.search(out.splitlines()[0]) ret = { 'destination': ip, 'gateway': m.group('gateway'), 'interface': m.group('interface'), 'source': m.group('source') } return ret if __grains__['kernel'] == 'SunOS': # [root@nacl ~]# route -n get 172.16.10.123 # route to: 172.16.10.123 #destination: 172.16.10.0 # mask: 255.255.255.0 # interface: net0 # flags: <UP,DONE,KERNEL> # recvpipe sendpipe ssthresh rtt,ms rttvar,ms hopcount mtu expire # 0 0 0 0 0 0 1500 0 cmd = '/usr/sbin/route -n get {0}'.format(ip) out = __salt__['cmd.run'](cmd, python_shell=False) ret = { 'destination': ip, 'gateway': None, 'interface': None, 'source': None } for line in out.splitlines(): line = line.split(':') if 'route to' in line[0]: ret['destination'] = line[1].strip() if 'gateway' in line[0]: ret['gateway'] = line[1].strip() if 'interface' in line[0]: ret['interface'] = line[1].strip() ret['source'] = salt.utils.network.interface_ip(line[1].strip()) return ret if __grains__['kernel'] == 'OpenBSD': # [root@exosphere] route -n get blackdot.be # route to: 5.135.127.100 #destination: default # mask: default # gateway: 192.168.0.1 # interface: vio0 # if address: 192.168.0.2 # priority: 8 (static) # flags: <UP,GATEWAY,DONE,STATIC> # use mtu expire # 8352657 0 0 cmd = 'route -n get {0}'.format(ip) out = __salt__['cmd.run'](cmd, python_shell=False) ret = { 'destination': ip, 'gateway': None, 'interface': None, 'source': None } for line in out.splitlines(): line = line.split(':') if 'route to' in line[0]: ret['destination'] = line[1].strip() if 'gateway' in line[0]: ret['gateway'] = line[1].strip() if 'interface' in line[0]: ret['interface'] = line[1].strip() if 'if address' in line[0]: ret['source'] = line[1].strip() return ret if __grains__['kernel'] == 'AIX': # root@la68pp002_pub:~# route -n get 172.29.149.95 # route to: 172.29.149.95 #destination: 172.29.149.95 # gateway: 127.0.0.1 # interface: lo0 #interf addr: 127.0.0.1 # flags: <UP,GATEWAY,HOST,DONE,STATIC> #recvpipe sendpipe ssthresh rtt,msec rttvar hopcount mtu expire # 0 0 0 0 0 0 0 -68642 cmd = 'route -n get {0}'.format(ip) out = __salt__['cmd.run'](cmd, python_shell=False) ret = { 'destination': ip, 'gateway': None, 'interface': None, 'source': None } for line in out.splitlines(): line = line.split(':') if 'route to' in line[0]: ret['destination'] = line[1].strip() if 'gateway' in line[0]: ret['gateway'] = line[1].strip() if 'interface' in line[0]: ret['interface'] = line[1].strip() if 'interf addr' in line[0]: ret['source'] = line[1].strip() return ret else: raise CommandExecutionError('Not yet supported on this platform')
python
def get_route(ip): ''' Return routing information for given destination ip .. versionadded:: 2015.5.3 .. versionchanged:: 2015.8.0 Added support for SunOS (Solaris 10, Illumos, SmartOS) Added support for OpenBSD .. versionchanged:: 2016.11.4 Added support for AIX CLI Example:: salt '*' network.get_route 10.10.10.10 ''' if __grains__['kernel'] == 'Linux': cmd = 'ip route get {0}'.format(ip) out = __salt__['cmd.run'](cmd, python_shell=True) regexp = re.compile(r'(via\s+(?P<gateway>[\w\.:]+))?\s+dev\s+(?P<interface>[\w\.\:\-]+)\s+.*src\s+(?P<source>[\w\.:]+)') m = regexp.search(out.splitlines()[0]) ret = { 'destination': ip, 'gateway': m.group('gateway'), 'interface': m.group('interface'), 'source': m.group('source') } return ret if __grains__['kernel'] == 'SunOS': # [root@nacl ~]# route -n get 172.16.10.123 # route to: 172.16.10.123 #destination: 172.16.10.0 # mask: 255.255.255.0 # interface: net0 # flags: <UP,DONE,KERNEL> # recvpipe sendpipe ssthresh rtt,ms rttvar,ms hopcount mtu expire # 0 0 0 0 0 0 1500 0 cmd = '/usr/sbin/route -n get {0}'.format(ip) out = __salt__['cmd.run'](cmd, python_shell=False) ret = { 'destination': ip, 'gateway': None, 'interface': None, 'source': None } for line in out.splitlines(): line = line.split(':') if 'route to' in line[0]: ret['destination'] = line[1].strip() if 'gateway' in line[0]: ret['gateway'] = line[1].strip() if 'interface' in line[0]: ret['interface'] = line[1].strip() ret['source'] = salt.utils.network.interface_ip(line[1].strip()) return ret if __grains__['kernel'] == 'OpenBSD': # [root@exosphere] route -n get blackdot.be # route to: 5.135.127.100 #destination: default # mask: default # gateway: 192.168.0.1 # interface: vio0 # if address: 192.168.0.2 # priority: 8 (static) # flags: <UP,GATEWAY,DONE,STATIC> # use mtu expire # 8352657 0 0 cmd = 'route -n get {0}'.format(ip) out = __salt__['cmd.run'](cmd, python_shell=False) ret = { 'destination': ip, 'gateway': None, 'interface': None, 'source': None } for line in out.splitlines(): line = line.split(':') if 'route to' in line[0]: ret['destination'] = line[1].strip() if 'gateway' in line[0]: ret['gateway'] = line[1].strip() if 'interface' in line[0]: ret['interface'] = line[1].strip() if 'if address' in line[0]: ret['source'] = line[1].strip() return ret if __grains__['kernel'] == 'AIX': # root@la68pp002_pub:~# route -n get 172.29.149.95 # route to: 172.29.149.95 #destination: 172.29.149.95 # gateway: 127.0.0.1 # interface: lo0 #interf addr: 127.0.0.1 # flags: <UP,GATEWAY,HOST,DONE,STATIC> #recvpipe sendpipe ssthresh rtt,msec rttvar hopcount mtu expire # 0 0 0 0 0 0 0 -68642 cmd = 'route -n get {0}'.format(ip) out = __salt__['cmd.run'](cmd, python_shell=False) ret = { 'destination': ip, 'gateway': None, 'interface': None, 'source': None } for line in out.splitlines(): line = line.split(':') if 'route to' in line[0]: ret['destination'] = line[1].strip() if 'gateway' in line[0]: ret['gateway'] = line[1].strip() if 'interface' in line[0]: ret['interface'] = line[1].strip() if 'interf addr' in line[0]: ret['source'] = line[1].strip() return ret else: raise CommandExecutionError('Not yet supported on this platform')
[ "def", "get_route", "(", "ip", ")", ":", "if", "__grains__", "[", "'kernel'", "]", "==", "'Linux'", ":", "cmd", "=", "'ip route get {0}'", ".", "format", "(", "ip", ")", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ",", "python_shell", "=...
Return routing information for given destination ip .. versionadded:: 2015.5.3 .. versionchanged:: 2015.8.0 Added support for SunOS (Solaris 10, Illumos, SmartOS) Added support for OpenBSD .. versionchanged:: 2016.11.4 Added support for AIX CLI Example:: salt '*' network.get_route 10.10.10.10
[ "Return", "routing", "information", "for", "given", "destination", "ip" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L1707-L1839
train
saltstack/salt
salt/modules/network.py
ifacestartswith
def ifacestartswith(cidr): ''' Retrieve the interface name from a specific CIDR .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' network.ifacestartswith 10.0 ''' net_list = interfaces() intfnames = [] pattern = six.text_type(cidr) size = len(pattern) for ifname, ifval in six.iteritems(net_list): if 'inet' in ifval: for inet in ifval['inet']: if inet['address'][0:size] == pattern: if 'label' in inet: intfnames.append(inet['label']) else: intfnames.append(ifname) return intfnames
python
def ifacestartswith(cidr): ''' Retrieve the interface name from a specific CIDR .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' network.ifacestartswith 10.0 ''' net_list = interfaces() intfnames = [] pattern = six.text_type(cidr) size = len(pattern) for ifname, ifval in six.iteritems(net_list): if 'inet' in ifval: for inet in ifval['inet']: if inet['address'][0:size] == pattern: if 'label' in inet: intfnames.append(inet['label']) else: intfnames.append(ifname) return intfnames
[ "def", "ifacestartswith", "(", "cidr", ")", ":", "net_list", "=", "interfaces", "(", ")", "intfnames", "=", "[", "]", "pattern", "=", "six", ".", "text_type", "(", "cidr", ")", "size", "=", "len", "(", "pattern", ")", "for", "ifname", ",", "ifval", "...
Retrieve the interface name from a specific CIDR .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' network.ifacestartswith 10.0
[ "Retrieve", "the", "interface", "name", "from", "a", "specific", "CIDR" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L1842-L1866
train
saltstack/salt
salt/modules/network.py
iphexval
def iphexval(ip): ''' Retrieve the hexadecimal representation of an IP address .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' network.iphexval 10.0.0.1 ''' a = ip.split('.') hexval = ['%02X' % int(x) for x in a] # pylint: disable=E1321 return ''.join(hexval)
python
def iphexval(ip): ''' Retrieve the hexadecimal representation of an IP address .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' network.iphexval 10.0.0.1 ''' a = ip.split('.') hexval = ['%02X' % int(x) for x in a] # pylint: disable=E1321 return ''.join(hexval)
[ "def", "iphexval", "(", "ip", ")", ":", "a", "=", "ip", ".", "split", "(", "'.'", ")", "hexval", "=", "[", "'%02X'", "%", "int", "(", "x", ")", "for", "x", "in", "a", "]", "# pylint: disable=E1321", "return", "''", ".", "join", "(", "hexval", ")"...
Retrieve the hexadecimal representation of an IP address .. versionadded:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' network.iphexval 10.0.0.1
[ "Retrieve", "the", "hexadecimal", "representation", "of", "an", "IP", "address" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/network.py#L1869-L1883
train
saltstack/salt
salt/states/boto_cloudwatch_event.py
present
def present(name, Name=None, ScheduleExpression=None, EventPattern=None, Description=None, RoleArn=None, State=None, Targets=None, region=None, key=None, keyid=None, profile=None): ''' Ensure trail exists. name The name of the state definition Name Name of the event rule. Defaults to the value of the 'name' param if not provided. ScheduleExpression The scheduling expression. For example, ``cron(0 20 * * ? *)``, "rate(5 minutes)" EventPattern The event pattern. Description A description of the rule State Indicates whether the rule is ENABLED or DISABLED. RoleArn The Amazon Resource Name (ARN) of the IAM role associated with the rule. Targets A list of rresources to be invoked when the rule is triggered. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': Name, 'result': True, 'comment': '', 'changes': {} } Name = Name if Name else name if isinstance(Targets, six.string_types): Targets = salt.utils.json.loads(Targets) if Targets is None: Targets = [] r = __salt__['boto_cloudwatch_event.exists'](Name=Name, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to create event rule: {0}.'.format(r['error']['message']) return ret if not r.get('exists'): if __opts__['test']: ret['comment'] = 'CloudWatch event rule {0} is set to be created.'.format(Name) ret['result'] = None return ret r = __salt__['boto_cloudwatch_event.create_or_update'](Name=Name, ScheduleExpression=ScheduleExpression, EventPattern=EventPattern, Description=Description, RoleArn=RoleArn, State=State, region=region, key=key, keyid=keyid, profile=profile) if not r.get('created'): ret['result'] = False ret['comment'] = 'Failed to create event rule: {0}.'.format(r['error']['message']) return ret _describe = __salt__['boto_cloudwatch_event.describe'](Name, region=region, key=key, keyid=keyid, profile=profile) if 'error' in _describe: ret['result'] = False ret['comment'] = 'Failed to create event rule: {0}.'.format(_describe['error']['message']) ret['changes'] = {} return ret ret['changes']['old'] = {'rule': None} ret['changes']['new'] = _describe ret['comment'] = 'CloudTrail {0} created.'.format(Name) if bool(Targets): r = __salt__['boto_cloudwatch_event.put_targets'](Rule=Name, Targets=Targets, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to create event rule: {0}.'.format(r['error']['message']) ret['changes'] = {} return ret ret['changes']['new']['rule']['Targets'] = Targets return ret ret['comment'] = os.linesep.join([ret['comment'], 'CloudWatch event rule {0} is present.'.format(Name)]) ret['changes'] = {} # trail exists, ensure config matches _describe = __salt__['boto_cloudwatch_event.describe'](Name=Name, region=region, key=key, keyid=keyid, profile=profile) if 'error' in _describe: ret['result'] = False ret['comment'] = 'Failed to update event rule: {0}.'.format(_describe['error']['message']) ret['changes'] = {} return ret _describe = _describe.get('rule') r = __salt__['boto_cloudwatch_event.list_targets'](Rule=Name, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to update event rule: {0}.'.format(r['error']['message']) ret['changes'] = {} return ret _describe['Targets'] = r.get('targets', []) need_update = False rule_vars = {'ScheduleExpression': 'ScheduleExpression', 'EventPattern': 'EventPattern', 'Description': 'Description', 'RoleArn': 'RoleArn', 'State': 'State', 'Targets': 'Targets'} for invar, outvar in six.iteritems(rule_vars): if _describe[outvar] != locals()[invar]: need_update = True ret['changes'].setdefault('new', {})[invar] = locals()[invar] ret['changes'].setdefault('old', {})[invar] = _describe[outvar] if need_update: if __opts__['test']: msg = 'CloudWatch event rule {0} set to be modified.'.format(Name) ret['comment'] = msg ret['result'] = None return ret ret['comment'] = os.linesep.join([ret['comment'], 'CloudWatch event rule to be modified']) r = __salt__['boto_cloudwatch_event.create_or_update'](Name=Name, ScheduleExpression=ScheduleExpression, EventPattern=EventPattern, Description=Description, RoleArn=RoleArn, State=State, region=region, key=key, keyid=keyid, profile=profile) if not r.get('created'): ret['result'] = False ret['comment'] = 'Failed to update event rule: {0}.'.format(r['error']['message']) ret['changes'] = {} return ret if _describe['Targets'] != Targets: removes = [i.get('Id') for i in _describe['Targets']] log.error(Targets) if bool(Targets): for target in Targets: tid = target.get('Id', None) if tid is not None and tid in removes: ix = removes.index(tid) removes.pop(ix) r = __salt__['boto_cloudwatch_event.put_targets'](Rule=Name, Targets=Targets, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to update event rule: {0}.'.format(r['error']['message']) ret['changes'] = {} return ret if bool(removes): r = __salt__['boto_cloudwatch_event.remove_targets'](Rule=Name, Ids=removes, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to update event rule: {0}.'.format(r['error']['message']) ret['changes'] = {} return ret return ret
python
def present(name, Name=None, ScheduleExpression=None, EventPattern=None, Description=None, RoleArn=None, State=None, Targets=None, region=None, key=None, keyid=None, profile=None): ''' Ensure trail exists. name The name of the state definition Name Name of the event rule. Defaults to the value of the 'name' param if not provided. ScheduleExpression The scheduling expression. For example, ``cron(0 20 * * ? *)``, "rate(5 minutes)" EventPattern The event pattern. Description A description of the rule State Indicates whether the rule is ENABLED or DISABLED. RoleArn The Amazon Resource Name (ARN) of the IAM role associated with the rule. Targets A list of rresources to be invoked when the rule is triggered. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': Name, 'result': True, 'comment': '', 'changes': {} } Name = Name if Name else name if isinstance(Targets, six.string_types): Targets = salt.utils.json.loads(Targets) if Targets is None: Targets = [] r = __salt__['boto_cloudwatch_event.exists'](Name=Name, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to create event rule: {0}.'.format(r['error']['message']) return ret if not r.get('exists'): if __opts__['test']: ret['comment'] = 'CloudWatch event rule {0} is set to be created.'.format(Name) ret['result'] = None return ret r = __salt__['boto_cloudwatch_event.create_or_update'](Name=Name, ScheduleExpression=ScheduleExpression, EventPattern=EventPattern, Description=Description, RoleArn=RoleArn, State=State, region=region, key=key, keyid=keyid, profile=profile) if not r.get('created'): ret['result'] = False ret['comment'] = 'Failed to create event rule: {0}.'.format(r['error']['message']) return ret _describe = __salt__['boto_cloudwatch_event.describe'](Name, region=region, key=key, keyid=keyid, profile=profile) if 'error' in _describe: ret['result'] = False ret['comment'] = 'Failed to create event rule: {0}.'.format(_describe['error']['message']) ret['changes'] = {} return ret ret['changes']['old'] = {'rule': None} ret['changes']['new'] = _describe ret['comment'] = 'CloudTrail {0} created.'.format(Name) if bool(Targets): r = __salt__['boto_cloudwatch_event.put_targets'](Rule=Name, Targets=Targets, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to create event rule: {0}.'.format(r['error']['message']) ret['changes'] = {} return ret ret['changes']['new']['rule']['Targets'] = Targets return ret ret['comment'] = os.linesep.join([ret['comment'], 'CloudWatch event rule {0} is present.'.format(Name)]) ret['changes'] = {} # trail exists, ensure config matches _describe = __salt__['boto_cloudwatch_event.describe'](Name=Name, region=region, key=key, keyid=keyid, profile=profile) if 'error' in _describe: ret['result'] = False ret['comment'] = 'Failed to update event rule: {0}.'.format(_describe['error']['message']) ret['changes'] = {} return ret _describe = _describe.get('rule') r = __salt__['boto_cloudwatch_event.list_targets'](Rule=Name, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to update event rule: {0}.'.format(r['error']['message']) ret['changes'] = {} return ret _describe['Targets'] = r.get('targets', []) need_update = False rule_vars = {'ScheduleExpression': 'ScheduleExpression', 'EventPattern': 'EventPattern', 'Description': 'Description', 'RoleArn': 'RoleArn', 'State': 'State', 'Targets': 'Targets'} for invar, outvar in six.iteritems(rule_vars): if _describe[outvar] != locals()[invar]: need_update = True ret['changes'].setdefault('new', {})[invar] = locals()[invar] ret['changes'].setdefault('old', {})[invar] = _describe[outvar] if need_update: if __opts__['test']: msg = 'CloudWatch event rule {0} set to be modified.'.format(Name) ret['comment'] = msg ret['result'] = None return ret ret['comment'] = os.linesep.join([ret['comment'], 'CloudWatch event rule to be modified']) r = __salt__['boto_cloudwatch_event.create_or_update'](Name=Name, ScheduleExpression=ScheduleExpression, EventPattern=EventPattern, Description=Description, RoleArn=RoleArn, State=State, region=region, key=key, keyid=keyid, profile=profile) if not r.get('created'): ret['result'] = False ret['comment'] = 'Failed to update event rule: {0}.'.format(r['error']['message']) ret['changes'] = {} return ret if _describe['Targets'] != Targets: removes = [i.get('Id') for i in _describe['Targets']] log.error(Targets) if bool(Targets): for target in Targets: tid = target.get('Id', None) if tid is not None and tid in removes: ix = removes.index(tid) removes.pop(ix) r = __salt__['boto_cloudwatch_event.put_targets'](Rule=Name, Targets=Targets, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to update event rule: {0}.'.format(r['error']['message']) ret['changes'] = {} return ret if bool(removes): r = __salt__['boto_cloudwatch_event.remove_targets'](Rule=Name, Ids=removes, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to update event rule: {0}.'.format(r['error']['message']) ret['changes'] = {} return ret return ret
[ "def", "present", "(", "name", ",", "Name", "=", "None", ",", "ScheduleExpression", "=", "None", ",", "EventPattern", "=", "None", ",", "Description", "=", "None", ",", "RoleArn", "=", "None", ",", "State", "=", "None", ",", "Targets", "=", "None", ","...
Ensure trail exists. name The name of the state definition Name Name of the event rule. Defaults to the value of the 'name' param if not provided. ScheduleExpression The scheduling expression. For example, ``cron(0 20 * * ? *)``, "rate(5 minutes)" EventPattern The event pattern. Description A description of the rule State Indicates whether the rule is ENABLED or DISABLED. RoleArn The Amazon Resource Name (ARN) of the IAM role associated with the rule. Targets A list of rresources to be invoked when the rule is triggered. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid.
[ "Ensure", "trail", "exists", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_cloudwatch_event.py#L76-L268
train
saltstack/salt
salt/states/boto_cloudwatch_event.py
absent
def absent(name, Name=None, region=None, key=None, keyid=None, profile=None): ''' Ensure CloudWatch event rule with passed properties is absent. name The name of the state definition. Name Name of the event rule. Defaults to the value of the 'name' param if not provided. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': Name, 'result': True, 'comment': '', 'changes': {} } Name = Name if Name else name r = __salt__['boto_cloudwatch_event.exists'](Name, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to delete event rule: {0}.'.format(r['error']['message']) return ret if r and not r['exists']: ret['comment'] = 'CloudWatch event rule {0} does not exist.'.format(Name) return ret if __opts__['test']: ret['comment'] = 'CloudWatch event rule {0} is set to be removed.'.format(Name) ret['result'] = None return ret # must remove all targets first r = __salt__['boto_cloudwatch_event.list_targets'](Rule=Name, region=region, key=key, keyid=keyid, profile=profile) if not r.get('targets'): ret['result'] = False ret['comment'] = 'Failed to delete event rule: {0}.'.format(r['error']['message']) return ret ids = [t.get('Id') for t in r['targets']] if bool(ids): r = __salt__['boto_cloudwatch_event.remove_targets'](Rule=Name, Ids=ids, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to delete event rule: {0}.'.format(r['error']['message']) return ret if r.get('failures'): ret['result'] = False ret['comment'] = 'Failed to delete event rule: {0}.'.format(r['failures']) return ret r = __salt__['boto_cloudwatch_event.delete'](Name, region=region, key=key, keyid=keyid, profile=profile) if not r['deleted']: ret['result'] = False ret['comment'] = 'Failed to delete event rule: {0}.'.format(r['error']['message']) return ret ret['changes']['old'] = {'rule': Name} ret['changes']['new'] = {'rule': None} ret['comment'] = 'CloudWatch event rule {0} deleted.'.format(Name) return ret
python
def absent(name, Name=None, region=None, key=None, keyid=None, profile=None): ''' Ensure CloudWatch event rule with passed properties is absent. name The name of the state definition. Name Name of the event rule. Defaults to the value of the 'name' param if not provided. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid. ''' ret = {'name': Name, 'result': True, 'comment': '', 'changes': {} } Name = Name if Name else name r = __salt__['boto_cloudwatch_event.exists'](Name, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to delete event rule: {0}.'.format(r['error']['message']) return ret if r and not r['exists']: ret['comment'] = 'CloudWatch event rule {0} does not exist.'.format(Name) return ret if __opts__['test']: ret['comment'] = 'CloudWatch event rule {0} is set to be removed.'.format(Name) ret['result'] = None return ret # must remove all targets first r = __salt__['boto_cloudwatch_event.list_targets'](Rule=Name, region=region, key=key, keyid=keyid, profile=profile) if not r.get('targets'): ret['result'] = False ret['comment'] = 'Failed to delete event rule: {0}.'.format(r['error']['message']) return ret ids = [t.get('Id') for t in r['targets']] if bool(ids): r = __salt__['boto_cloudwatch_event.remove_targets'](Rule=Name, Ids=ids, region=region, key=key, keyid=keyid, profile=profile) if 'error' in r: ret['result'] = False ret['comment'] = 'Failed to delete event rule: {0}.'.format(r['error']['message']) return ret if r.get('failures'): ret['result'] = False ret['comment'] = 'Failed to delete event rule: {0}.'.format(r['failures']) return ret r = __salt__['boto_cloudwatch_event.delete'](Name, region=region, key=key, keyid=keyid, profile=profile) if not r['deleted']: ret['result'] = False ret['comment'] = 'Failed to delete event rule: {0}.'.format(r['error']['message']) return ret ret['changes']['old'] = {'rule': Name} ret['changes']['new'] = {'rule': None} ret['comment'] = 'CloudWatch event rule {0} deleted.'.format(Name) return ret
[ "def", "absent", "(", "name", ",", "Name", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "Name", ",", "'result'", ":", "True", ...
Ensure CloudWatch event rule with passed properties is absent. name The name of the state definition. Name Name of the event rule. Defaults to the value of the 'name' param if not provided. region Region to connect to. key Secret key to be used. keyid Access key to be used. profile A dict with region, key and keyid, or a pillar key (string) that contains a dict with region, key and keyid.
[ "Ensure", "CloudWatch", "event", "rule", "with", "passed", "properties", "is", "absent", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/boto_cloudwatch_event.py#L271-L352
train
saltstack/salt
salt/modules/libcloud_compute.py
list_nodes
def list_nodes(profile, **libcloud_kwargs): ''' Return a list of nodes :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_nodes method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.list_nodes profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) nodes = conn.list_nodes(**libcloud_kwargs) ret = [] for node in nodes: ret.append(_simple_node(node)) return ret
python
def list_nodes(profile, **libcloud_kwargs): ''' Return a list of nodes :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_nodes method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.list_nodes profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) nodes = conn.list_nodes(**libcloud_kwargs) ret = [] for node in nodes: ret.append(_simple_node(node)) return ret
[ "def", "list_nodes", "(", "profile", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "salt", ".", "utils", ".", "args", ".", "clean_kwargs", "(", "*", "*", "libcloud_kwarg...
Return a list of nodes :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_nodes method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.list_nodes profile1
[ "Return", "a", "list", "of", "nodes" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_compute.py#L93-L115
train
saltstack/salt
salt/modules/libcloud_compute.py
list_sizes
def list_sizes(profile, location_id=None, **libcloud_kwargs): ''' Return a list of node sizes :param profile: The profile key :type profile: ``str`` :param location_id: The location key, from list_locations :type location_id: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_sizes method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.list_sizes profile1 salt myminion libcloud_compute.list_sizes profile1 us-east1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) if location_id is not None: locations = [loc for loc in conn.list_locations() if loc.id == location_id] if not locations: raise ValueError("Location not found") else: sizes = conn.list_sizes(location=locations[0], **libcloud_kwargs) else: sizes = conn.list_sizes(**libcloud_kwargs) ret = [] for size in sizes: ret.append(_simple_size(size)) return ret
python
def list_sizes(profile, location_id=None, **libcloud_kwargs): ''' Return a list of node sizes :param profile: The profile key :type profile: ``str`` :param location_id: The location key, from list_locations :type location_id: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_sizes method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.list_sizes profile1 salt myminion libcloud_compute.list_sizes profile1 us-east1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) if location_id is not None: locations = [loc for loc in conn.list_locations() if loc.id == location_id] if not locations: raise ValueError("Location not found") else: sizes = conn.list_sizes(location=locations[0], **libcloud_kwargs) else: sizes = conn.list_sizes(**libcloud_kwargs) ret = [] for size in sizes: ret.append(_simple_size(size)) return ret
[ "def", "list_sizes", "(", "profile", ",", "location_id", "=", "None", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "salt", ".", "utils", ".", "args", ".", "clean_kwargs...
Return a list of node sizes :param profile: The profile key :type profile: ``str`` :param location_id: The location key, from list_locations :type location_id: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_sizes method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.list_sizes profile1 salt myminion libcloud_compute.list_sizes profile1 us-east1
[ "Return", "a", "list", "of", "node", "sizes" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_compute.py#L118-L152
train
saltstack/salt
salt/modules/libcloud_compute.py
list_locations
def list_locations(profile, **libcloud_kwargs): ''' Return a list of locations for this cloud :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_locations method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.list_locations profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) locations = conn.list_locations(**libcloud_kwargs) ret = [] for loc in locations: ret.append(_simple_location(loc)) return ret
python
def list_locations(profile, **libcloud_kwargs): ''' Return a list of locations for this cloud :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_locations method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.list_locations profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) locations = conn.list_locations(**libcloud_kwargs) ret = [] for loc in locations: ret.append(_simple_location(loc)) return ret
[ "def", "list_locations", "(", "profile", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "salt", ".", "utils", ".", "args", ".", "clean_kwargs", "(", "*", "*", "libcloud_k...
Return a list of locations for this cloud :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_locations method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.list_locations profile1
[ "Return", "a", "list", "of", "locations", "for", "this", "cloud" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_compute.py#L155-L178
train
saltstack/salt
salt/modules/libcloud_compute.py
reboot_node
def reboot_node(node_id, profile, **libcloud_kwargs): ''' Reboot a node in the cloud :param node_id: Unique ID of the node to reboot :type node_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's reboot_node method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.reboot_node as-2346 profile1 ''' conn = _get_driver(profile=profile) node = _get_by_id(conn.list_nodes(**libcloud_kwargs), node_id) return conn.reboot_node(node, **libcloud_kwargs)
python
def reboot_node(node_id, profile, **libcloud_kwargs): ''' Reboot a node in the cloud :param node_id: Unique ID of the node to reboot :type node_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's reboot_node method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.reboot_node as-2346 profile1 ''' conn = _get_driver(profile=profile) node = _get_by_id(conn.list_nodes(**libcloud_kwargs), node_id) return conn.reboot_node(node, **libcloud_kwargs)
[ "def", "reboot_node", "(", "node_id", ",", "profile", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "node", "=", "_get_by_id", "(", "conn", ".", "list_nodes", "(", "*", "*", "libcloud_kwargs", ...
Reboot a node in the cloud :param node_id: Unique ID of the node to reboot :type node_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's reboot_node method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.reboot_node as-2346 profile1
[ "Reboot", "a", "node", "in", "the", "cloud" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_compute.py#L181-L202
train
saltstack/salt
salt/modules/libcloud_compute.py
list_volumes
def list_volumes(profile, **libcloud_kwargs): ''' Return a list of storage volumes for this cloud :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_volumes method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.list_volumes profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) volumes = conn.list_volumes(**libcloud_kwargs) ret = [] for volume in volumes: ret.append(_simple_volume(volume)) return ret
python
def list_volumes(profile, **libcloud_kwargs): ''' Return a list of storage volumes for this cloud :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_volumes method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.list_volumes profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) volumes = conn.list_volumes(**libcloud_kwargs) ret = [] for volume in volumes: ret.append(_simple_volume(volume)) return ret
[ "def", "list_volumes", "(", "profile", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "salt", ".", "utils", ".", "args", ".", "clean_kwargs", "(", "*", "*", "libcloud_kwa...
Return a list of storage volumes for this cloud :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_volumes method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.list_volumes profile1
[ "Return", "a", "list", "of", "storage", "volumes", "for", "this", "cloud" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_compute.py#L229-L252
train
saltstack/salt
salt/modules/libcloud_compute.py
list_volume_snapshots
def list_volume_snapshots(volume_id, profile, **libcloud_kwargs): ''' Return a list of storage volumes snapshots for this cloud :param volume_id: The volume identifier :type volume_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_volume_snapshots method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.list_volume_snapshots vol1 profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) volume = _get_by_id(conn.list_volumes(), volume_id) snapshots = conn.list_volume_snapshots(volume, **libcloud_kwargs) ret = [] for snapshot in snapshots: ret.append(_simple_volume_snapshot(snapshot)) return ret
python
def list_volume_snapshots(volume_id, profile, **libcloud_kwargs): ''' Return a list of storage volumes snapshots for this cloud :param volume_id: The volume identifier :type volume_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_volume_snapshots method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.list_volume_snapshots vol1 profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) volume = _get_by_id(conn.list_volumes(), volume_id) snapshots = conn.list_volume_snapshots(volume, **libcloud_kwargs) ret = [] for snapshot in snapshots: ret.append(_simple_volume_snapshot(snapshot)) return ret
[ "def", "list_volume_snapshots", "(", "volume_id", ",", "profile", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "salt", ".", "utils", ".", "args", ".", "clean_kwargs", "("...
Return a list of storage volumes snapshots for this cloud :param volume_id: The volume identifier :type volume_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_volume_snapshots method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.list_volume_snapshots vol1 profile1
[ "Return", "a", "list", "of", "storage", "volumes", "snapshots", "for", "this", "cloud" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_compute.py#L255-L282
train
saltstack/salt
salt/modules/libcloud_compute.py
create_volume
def create_volume(size, name, profile, location_id=None, **libcloud_kwargs): ''' Create a storage volume :param size: Size of volume in gigabytes (required) :type size: ``int`` :param name: Name of the volume to be created :type name: ``str`` :param location_id: Which data center to create a volume in. If empty, undefined behavior will be selected. (optional) :type location_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_volumes method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.create_volume 1000 vol1 profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) if location_id is not None: location = _get_by_id(conn.list_locations(), location_id) else: location = None # TODO : Support creating from volume snapshot volume = conn.create_volume(size, name, location, snapshot=None, **libcloud_kwargs) return _simple_volume(volume)
python
def create_volume(size, name, profile, location_id=None, **libcloud_kwargs): ''' Create a storage volume :param size: Size of volume in gigabytes (required) :type size: ``int`` :param name: Name of the volume to be created :type name: ``str`` :param location_id: Which data center to create a volume in. If empty, undefined behavior will be selected. (optional) :type location_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_volumes method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.create_volume 1000 vol1 profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) if location_id is not None: location = _get_by_id(conn.list_locations(), location_id) else: location = None # TODO : Support creating from volume snapshot volume = conn.create_volume(size, name, location, snapshot=None, **libcloud_kwargs) return _simple_volume(volume)
[ "def", "create_volume", "(", "size", ",", "name", ",", "profile", ",", "location_id", "=", "None", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "salt", ".", "utils", ...
Create a storage volume :param size: Size of volume in gigabytes (required) :type size: ``int`` :param name: Name of the volume to be created :type name: ``str`` :param location_id: Which data center to create a volume in. If empty, undefined behavior will be selected. (optional) :type location_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_volumes method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.create_volume 1000 vol1 profile1
[ "Create", "a", "storage", "volume" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_compute.py#L285-L321
train
saltstack/salt
salt/modules/libcloud_compute.py
create_volume_snapshot
def create_volume_snapshot(volume_id, profile, name=None, **libcloud_kwargs): ''' Create a storage volume snapshot :param volume_id: Volume ID from which to create the new snapshot. :type volume_id: ``str`` :param profile: The profile key :type profile: ``str`` :param name: Name of the snapshot to be created (optional) :type name: ``str`` :param libcloud_kwargs: Extra arguments for the driver's create_volume_snapshot method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.create_volume_snapshot vol1 profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) volume = _get_by_id(conn.list_volumes(), volume_id) snapshot = conn.create_volume_snapshot(volume, name=name, **libcloud_kwargs) return _simple_volume_snapshot(snapshot)
python
def create_volume_snapshot(volume_id, profile, name=None, **libcloud_kwargs): ''' Create a storage volume snapshot :param volume_id: Volume ID from which to create the new snapshot. :type volume_id: ``str`` :param profile: The profile key :type profile: ``str`` :param name: Name of the snapshot to be created (optional) :type name: ``str`` :param libcloud_kwargs: Extra arguments for the driver's create_volume_snapshot method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.create_volume_snapshot vol1 profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) volume = _get_by_id(conn.list_volumes(), volume_id) snapshot = conn.create_volume_snapshot(volume, name=name, **libcloud_kwargs) return _simple_volume_snapshot(snapshot)
[ "def", "create_volume_snapshot", "(", "volume_id", ",", "profile", ",", "name", "=", "None", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "salt", ".", "utils", ".", "ar...
Create a storage volume snapshot :param volume_id: Volume ID from which to create the new snapshot. :type volume_id: ``str`` :param profile: The profile key :type profile: ``str`` :param name: Name of the snapshot to be created (optional) :type name: ``str`` :param libcloud_kwargs: Extra arguments for the driver's create_volume_snapshot method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.create_volume_snapshot vol1 profile1
[ "Create", "a", "storage", "volume", "snapshot" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_compute.py#L324-L352
train
saltstack/salt
salt/modules/libcloud_compute.py
attach_volume
def attach_volume(node_id, volume_id, profile, device=None, **libcloud_kwargs): ''' Attaches volume to node. :param node_id: Node ID to target :type node_id: ``str`` :param volume_id: Volume ID from which to attach :type volume_id: ``str`` :param profile: The profile key :type profile: ``str`` :param device: Where the device is exposed, e.g. '/dev/sdb' :type device: ``str`` :param libcloud_kwargs: Extra arguments for the driver's attach_volume method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.detach_volume vol1 profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) volume = _get_by_id(conn.list_volumes(), volume_id) node = _get_by_id(conn.list_nodes(), node_id) return conn.attach_volume(node, volume, device=device, **libcloud_kwargs)
python
def attach_volume(node_id, volume_id, profile, device=None, **libcloud_kwargs): ''' Attaches volume to node. :param node_id: Node ID to target :type node_id: ``str`` :param volume_id: Volume ID from which to attach :type volume_id: ``str`` :param profile: The profile key :type profile: ``str`` :param device: Where the device is exposed, e.g. '/dev/sdb' :type device: ``str`` :param libcloud_kwargs: Extra arguments for the driver's attach_volume method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.detach_volume vol1 profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) volume = _get_by_id(conn.list_volumes(), volume_id) node = _get_by_id(conn.list_nodes(), node_id) return conn.attach_volume(node, volume, device=device, **libcloud_kwargs)
[ "def", "attach_volume", "(", "node_id", ",", "volume_id", ",", "profile", ",", "device", "=", "None", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "salt", ".", "utils",...
Attaches volume to node. :param node_id: Node ID to target :type node_id: ``str`` :param volume_id: Volume ID from which to attach :type volume_id: ``str`` :param profile: The profile key :type profile: ``str`` :param device: Where the device is exposed, e.g. '/dev/sdb' :type device: ``str`` :param libcloud_kwargs: Extra arguments for the driver's attach_volume method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.detach_volume vol1 profile1
[ "Attaches", "volume", "to", "node", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_compute.py#L355-L384
train
saltstack/salt
salt/modules/libcloud_compute.py
detach_volume
def detach_volume(volume_id, profile, **libcloud_kwargs): ''' Detaches a volume from a node. :param volume_id: Volume ID from which to detach :type volume_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's detach_volume method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.detach_volume vol1 profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) volume = _get_by_id(conn.list_volumes(), volume_id) return conn.detach_volume(volume, **libcloud_kwargs)
python
def detach_volume(volume_id, profile, **libcloud_kwargs): ''' Detaches a volume from a node. :param volume_id: Volume ID from which to detach :type volume_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's detach_volume method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.detach_volume vol1 profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) volume = _get_by_id(conn.list_volumes(), volume_id) return conn.detach_volume(volume, **libcloud_kwargs)
[ "def", "detach_volume", "(", "volume_id", ",", "profile", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "salt", ".", "utils", ".", "args", ".", "clean_kwargs", "(", "*",...
Detaches a volume from a node. :param volume_id: Volume ID from which to detach :type volume_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's detach_volume method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.detach_volume vol1 profile1
[ "Detaches", "a", "volume", "from", "a", "node", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_compute.py#L387-L409
train
saltstack/salt
salt/modules/libcloud_compute.py
destroy_volume_snapshot
def destroy_volume_snapshot(volume_id, snapshot_id, profile, **libcloud_kwargs): ''' Destroy a volume snapshot. :param volume_id: Volume ID from which the snapshot belongs :type volume_id: ``str`` :param snapshot_id: Volume Snapshot ID from which to destroy :type snapshot_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's destroy_volume_snapshot method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.destroy_volume_snapshot snap1 profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) volume = _get_by_id(conn.list_volumes(), volume_id) snapshot = _get_by_id(conn.list_volume_snapshots(volume), snapshot_id) return conn.destroy_volume_snapshot(snapshot, **libcloud_kwargs)
python
def destroy_volume_snapshot(volume_id, snapshot_id, profile, **libcloud_kwargs): ''' Destroy a volume snapshot. :param volume_id: Volume ID from which the snapshot belongs :type volume_id: ``str`` :param snapshot_id: Volume Snapshot ID from which to destroy :type snapshot_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's destroy_volume_snapshot method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.destroy_volume_snapshot snap1 profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) volume = _get_by_id(conn.list_volumes(), volume_id) snapshot = _get_by_id(conn.list_volume_snapshots(volume), snapshot_id) return conn.destroy_volume_snapshot(snapshot, **libcloud_kwargs)
[ "def", "destroy_volume_snapshot", "(", "volume_id", ",", "snapshot_id", ",", "profile", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "salt", ".", "utils", ".", "args", "....
Destroy a volume snapshot. :param volume_id: Volume ID from which the snapshot belongs :type volume_id: ``str`` :param snapshot_id: Volume Snapshot ID from which to destroy :type snapshot_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's destroy_volume_snapshot method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.destroy_volume_snapshot snap1 profile1
[ "Destroy", "a", "volume", "snapshot", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_compute.py#L437-L463
train
saltstack/salt
salt/modules/libcloud_compute.py
list_images
def list_images(profile, location_id=None, **libcloud_kwargs): ''' Return a list of images for this cloud :param profile: The profile key :type profile: ``str`` :param location_id: The location key, from list_locations :type location_id: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_images method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.list_images profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) if location_id is not None: location = _get_by_id(conn.list_locations(), location_id) else: location = None images = conn.list_images(location=location, **libcloud_kwargs) ret = [] for image in images: ret.append(_simple_image(image)) return ret
python
def list_images(profile, location_id=None, **libcloud_kwargs): ''' Return a list of images for this cloud :param profile: The profile key :type profile: ``str`` :param location_id: The location key, from list_locations :type location_id: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_images method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.list_images profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) if location_id is not None: location = _get_by_id(conn.list_locations(), location_id) else: location = None images = conn.list_images(location=location, **libcloud_kwargs) ret = [] for image in images: ret.append(_simple_image(image)) return ret
[ "def", "list_images", "(", "profile", ",", "location_id", "=", "None", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "salt", ".", "utils", ".", "args", ".", "clean_kwarg...
Return a list of images for this cloud :param profile: The profile key :type profile: ``str`` :param location_id: The location key, from list_locations :type location_id: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_images method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.list_images profile1
[ "Return", "a", "list", "of", "images", "for", "this", "cloud" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_compute.py#L466-L496
train
saltstack/salt
salt/modules/libcloud_compute.py
create_image
def create_image(node_id, name, profile, description=None, **libcloud_kwargs): ''' Create an image from a node :param node_id: Node to run the task on. :type node_id: ``str`` :param name: name for new image. :type name: ``str`` :param profile: The profile key :type profile: ``str`` :param description: description for new image. :type description: ``description`` :param libcloud_kwargs: Extra arguments for the driver's create_image method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.create_image server1 my_image profile1 salt myminion libcloud_compute.create_image server1 my_image profile1 description='test image' ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) node = _get_by_id(conn.list_nodes(), node_id) return _simple_image(conn.create_image(node, name, description=description, **libcloud_kwargs))
python
def create_image(node_id, name, profile, description=None, **libcloud_kwargs): ''' Create an image from a node :param node_id: Node to run the task on. :type node_id: ``str`` :param name: name for new image. :type name: ``str`` :param profile: The profile key :type profile: ``str`` :param description: description for new image. :type description: ``description`` :param libcloud_kwargs: Extra arguments for the driver's create_image method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.create_image server1 my_image profile1 salt myminion libcloud_compute.create_image server1 my_image profile1 description='test image' ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) node = _get_by_id(conn.list_nodes(), node_id) return _simple_image(conn.create_image(node, name, description=description, **libcloud_kwargs))
[ "def", "create_image", "(", "node_id", ",", "name", ",", "profile", ",", "description", "=", "None", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "salt", ".", "utils", ...
Create an image from a node :param node_id: Node to run the task on. :type node_id: ``str`` :param name: name for new image. :type name: ``str`` :param profile: The profile key :type profile: ``str`` :param description: description for new image. :type description: ``description`` :param libcloud_kwargs: Extra arguments for the driver's create_image method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.create_image server1 my_image profile1 salt myminion libcloud_compute.create_image server1 my_image profile1 description='test image'
[ "Create", "an", "image", "from", "a", "node" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_compute.py#L499-L528
train
saltstack/salt
salt/modules/libcloud_compute.py
delete_image
def delete_image(image_id, profile, **libcloud_kwargs): ''' Delete an image of a node :param image_id: Image to delete :type image_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_image method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.delete_image image1 profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) image = _get_by_id(conn.list_images(), image_id) return conn.delete_image(image, **libcloud_kwargs)
python
def delete_image(image_id, profile, **libcloud_kwargs): ''' Delete an image of a node :param image_id: Image to delete :type image_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_image method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.delete_image image1 profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) image = _get_by_id(conn.list_images(), image_id) return conn.delete_image(image, **libcloud_kwargs)
[ "def", "delete_image", "(", "image_id", ",", "profile", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "salt", ".", "utils", ".", "args", ".", "clean_kwargs", "(", "*", ...
Delete an image of a node :param image_id: Image to delete :type image_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_image method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.delete_image image1 profile1
[ "Delete", "an", "image", "of", "a", "node" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_compute.py#L531-L553
train
saltstack/salt
salt/modules/libcloud_compute.py
get_image
def get_image(image_id, profile, **libcloud_kwargs): ''' Get an image of a node :param image_id: Image to fetch :type image_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_image method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.get_image image1 profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) image = conn.get_image(image_id, **libcloud_kwargs) return _simple_image(image)
python
def get_image(image_id, profile, **libcloud_kwargs): ''' Get an image of a node :param image_id: Image to fetch :type image_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_image method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.get_image image1 profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) image = conn.get_image(image_id, **libcloud_kwargs) return _simple_image(image)
[ "def", "get_image", "(", "image_id", ",", "profile", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "salt", ".", "utils", ".", "args", ".", "clean_kwargs", "(", "*", "*...
Get an image of a node :param image_id: Image to fetch :type image_id: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_image method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.get_image image1 profile1
[ "Get", "an", "image", "of", "a", "node" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_compute.py#L556-L578
train
saltstack/salt
salt/modules/libcloud_compute.py
copy_image
def copy_image(source_region, image_id, name, profile, description=None, **libcloud_kwargs): ''' Copies an image from a source region to the current region. :param source_region: Region to copy the node from. :type source_region: ``str`` :param image_id: Image to copy. :type image_id: ``str`` :param name: name for new image. :type name: ``str`` :param profile: The profile key :type profile: ``str`` :param description: description for new image. :type name: ``str`` :param libcloud_kwargs: Extra arguments for the driver's copy_image method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.copy_image us-east1 image1 'new image' profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) image = conn.get_image(image_id, **libcloud_kwargs) new_image = conn.copy_image(source_region, image, name, description=description, **libcloud_kwargs) return _simple_image(new_image)
python
def copy_image(source_region, image_id, name, profile, description=None, **libcloud_kwargs): ''' Copies an image from a source region to the current region. :param source_region: Region to copy the node from. :type source_region: ``str`` :param image_id: Image to copy. :type image_id: ``str`` :param name: name for new image. :type name: ``str`` :param profile: The profile key :type profile: ``str`` :param description: description for new image. :type name: ``str`` :param libcloud_kwargs: Extra arguments for the driver's copy_image method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.copy_image us-east1 image1 'new image' profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) image = conn.get_image(image_id, **libcloud_kwargs) new_image = conn.copy_image(source_region, image, name, description=description, **libcloud_kwargs) return _simple_image(new_image)
[ "def", "copy_image", "(", "source_region", ",", "image_id", ",", "name", ",", "profile", ",", "description", "=", "None", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "...
Copies an image from a source region to the current region. :param source_region: Region to copy the node from. :type source_region: ``str`` :param image_id: Image to copy. :type image_id: ``str`` :param name: name for new image. :type name: ``str`` :param profile: The profile key :type profile: ``str`` :param description: description for new image. :type name: ``str`` :param libcloud_kwargs: Extra arguments for the driver's copy_image method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.copy_image us-east1 image1 'new image' profile1
[ "Copies", "an", "image", "from", "a", "source", "region", "to", "the", "current", "region", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_compute.py#L581-L614
train
saltstack/salt
salt/modules/libcloud_compute.py
list_key_pairs
def list_key_pairs(profile, **libcloud_kwargs): ''' List all the available key pair objects. :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_key_pairs method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.list_key_pairs profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) keys = conn.list_key_pairs(**libcloud_kwargs) ret = [] for key in keys: ret.append(_simple_key_pair(key)) return ret
python
def list_key_pairs(profile, **libcloud_kwargs): ''' List all the available key pair objects. :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_key_pairs method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.list_key_pairs profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) keys = conn.list_key_pairs(**libcloud_kwargs) ret = [] for key in keys: ret.append(_simple_key_pair(key)) return ret
[ "def", "list_key_pairs", "(", "profile", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "salt", ".", "utils", ".", "args", ".", "clean_kwargs", "(", "*", "*", "libcloud_k...
List all the available key pair objects. :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's list_key_pairs method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.list_key_pairs profile1
[ "List", "all", "the", "available", "key", "pair", "objects", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_compute.py#L617-L640
train
saltstack/salt
salt/modules/libcloud_compute.py
get_key_pair
def get_key_pair(name, profile, **libcloud_kwargs): ''' Get a single key pair by name :param name: Name of the key pair to retrieve. :type name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's get_key_pair method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.get_key_pair pair1 profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) return _simple_key_pair(conn.get_key_pair(name, **libcloud_kwargs))
python
def get_key_pair(name, profile, **libcloud_kwargs): ''' Get a single key pair by name :param name: Name of the key pair to retrieve. :type name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's get_key_pair method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.get_key_pair pair1 profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) return _simple_key_pair(conn.get_key_pair(name, **libcloud_kwargs))
[ "def", "get_key_pair", "(", "name", ",", "profile", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "salt", ".", "utils", ".", "args", ".", "clean_kwargs", "(", "*", "*"...
Get a single key pair by name :param name: Name of the key pair to retrieve. :type name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's get_key_pair method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.get_key_pair pair1 profile1
[ "Get", "a", "single", "key", "pair", "by", "name" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_compute.py#L643-L664
train
saltstack/salt
salt/modules/libcloud_compute.py
import_key_pair
def import_key_pair(name, key, profile, key_type=None, **libcloud_kwargs): ''' Import a new public key from string or a file path :param name: Key pair name. :type name: ``str`` :param key: Public key material, the string or a path to a file :type key: ``str`` or path ``str`` :param profile: The profile key :type profile: ``str`` :param key_type: The key pair type, either `FILE` or `STRING`. Will detect if not provided and assume that if the string is a path to an existing path it is a FILE, else STRING. :type key_type: ``str`` :param libcloud_kwargs: Extra arguments for the driver's import_key_pair_from_xxx method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.import_key_pair pair1 key_value_data123 profile1 salt myminion libcloud_compute.import_key_pair pair1 /path/to/key profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) if os.path.exists(key) or key_type == 'FILE': return _simple_key_pair(conn.import_key_pair_from_file(name, key, **libcloud_kwargs)) else: return _simple_key_pair(conn.import_key_pair_from_string(name, key, **libcloud_kwargs))
python
def import_key_pair(name, key, profile, key_type=None, **libcloud_kwargs): ''' Import a new public key from string or a file path :param name: Key pair name. :type name: ``str`` :param key: Public key material, the string or a path to a file :type key: ``str`` or path ``str`` :param profile: The profile key :type profile: ``str`` :param key_type: The key pair type, either `FILE` or `STRING`. Will detect if not provided and assume that if the string is a path to an existing path it is a FILE, else STRING. :type key_type: ``str`` :param libcloud_kwargs: Extra arguments for the driver's import_key_pair_from_xxx method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.import_key_pair pair1 key_value_data123 profile1 salt myminion libcloud_compute.import_key_pair pair1 /path/to/key profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) if os.path.exists(key) or key_type == 'FILE': return _simple_key_pair(conn.import_key_pair_from_file(name, key, **libcloud_kwargs)) else: return _simple_key_pair(conn.import_key_pair_from_string(name, key, **libcloud_kwargs))
[ "def", "import_key_pair", "(", "name", ",", "key", ",", "profile", ",", "key_type", "=", "None", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "salt", ".", "utils", "....
Import a new public key from string or a file path :param name: Key pair name. :type name: ``str`` :param key: Public key material, the string or a path to a file :type key: ``str`` or path ``str`` :param profile: The profile key :type profile: ``str`` :param key_type: The key pair type, either `FILE` or `STRING`. Will detect if not provided and assume that if the string is a path to an existing path it is a FILE, else STRING. :type key_type: ``str`` :param libcloud_kwargs: Extra arguments for the driver's import_key_pair_from_xxx method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.import_key_pair pair1 key_value_data123 profile1 salt myminion libcloud_compute.import_key_pair pair1 /path/to/key profile1
[ "Import", "a", "new", "public", "key", "from", "string", "or", "a", "file", "path" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_compute.py#L691-L727
train
saltstack/salt
salt/modules/libcloud_compute.py
delete_key_pair
def delete_key_pair(name, profile, **libcloud_kwargs): ''' Delete a key pair :param name: Key pair name. :type name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's import_key_pair_from_xxx method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.delete_key_pair pair1 profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) key = conn.get_key_pair(name) return conn.delete_key_pair(key, **libcloud_kwargs)
python
def delete_key_pair(name, profile, **libcloud_kwargs): ''' Delete a key pair :param name: Key pair name. :type name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's import_key_pair_from_xxx method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.delete_key_pair pair1 profile1 ''' conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) key = conn.get_key_pair(name) return conn.delete_key_pair(key, **libcloud_kwargs)
[ "def", "delete_key_pair", "(", "name", ",", "profile", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "salt", ".", "utils", ".", "args", ".", "clean_kwargs", "(", "*", ...
Delete a key pair :param name: Key pair name. :type name: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's import_key_pair_from_xxx method :type libcloud_kwargs: ``dict`` CLI Example: .. code-block:: bash salt myminion libcloud_compute.delete_key_pair pair1 profile1
[ "Delete", "a", "key", "pair" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_compute.py#L730-L752
train
saltstack/salt
salt/modules/libcloud_compute.py
_get_by_id
def _get_by_id(collection, id): ''' Get item from a list by the id field ''' matches = [item for item in collection if item.id == id] if not matches: raise ValueError('Could not find a matching item') elif len(matches) > 1: raise ValueError('The id matched {0} items, not 1'.format(len(matches))) return matches[0]
python
def _get_by_id(collection, id): ''' Get item from a list by the id field ''' matches = [item for item in collection if item.id == id] if not matches: raise ValueError('Could not find a matching item') elif len(matches) > 1: raise ValueError('The id matched {0} items, not 1'.format(len(matches))) return matches[0]
[ "def", "_get_by_id", "(", "collection", ",", "id", ")", ":", "matches", "=", "[", "item", "for", "item", "in", "collection", "if", "item", ".", "id", "==", "id", "]", "if", "not", "matches", ":", "raise", "ValueError", "(", "'Could not find a matching item...
Get item from a list by the id field
[ "Get", "item", "from", "a", "list", "by", "the", "id", "field" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_compute.py#L780-L789
train
saltstack/salt
salt/states/monit.py
monitor
def monitor(name): ''' Get the summary from module monit and try to see if service is being monitored. If not then monitor the service. ''' ret = {'result': None, 'name': name, 'comment': '', 'changes': {} } result = __salt__['monit.summary'](name) try: for key, value in result.items(): if 'Running' in value[name]: ret['comment'] = ('{0} is being being monitored.').format(name) ret['result'] = True else: if __opts__['test']: ret['comment'] = 'Service {0} is set to be monitored.'.format(name) ret['result'] = None return ret __salt__['monit.monitor'](name) ret['comment'] = ('{0} started to be monitored.').format(name) ret['changes'][name] = 'Running' ret['result'] = True break except KeyError: ret['comment'] = ('{0} not found in configuration.').format(name) ret['result'] = False return ret
python
def monitor(name): ''' Get the summary from module monit and try to see if service is being monitored. If not then monitor the service. ''' ret = {'result': None, 'name': name, 'comment': '', 'changes': {} } result = __salt__['monit.summary'](name) try: for key, value in result.items(): if 'Running' in value[name]: ret['comment'] = ('{0} is being being monitored.').format(name) ret['result'] = True else: if __opts__['test']: ret['comment'] = 'Service {0} is set to be monitored.'.format(name) ret['result'] = None return ret __salt__['monit.monitor'](name) ret['comment'] = ('{0} started to be monitored.').format(name) ret['changes'][name] = 'Running' ret['result'] = True break except KeyError: ret['comment'] = ('{0} not found in configuration.').format(name) ret['result'] = False return ret
[ "def", "monitor", "(", "name", ")", ":", "ret", "=", "{", "'result'", ":", "None", ",", "'name'", ":", "name", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{", "}", "}", "result", "=", "__salt__", "[", "'monit.summary'", "]", "(", "name", "...
Get the summary from module monit and try to see if service is being monitored. If not then monitor the service.
[ "Get", "the", "summary", "from", "module", "monit", "and", "try", "to", "see", "if", "service", "is", "being", "monitored", ".", "If", "not", "then", "monitor", "the", "service", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/monit.py#L34-L65
train
saltstack/salt
salt/modules/jboss7.py
status
def status(jboss_config, host=None, server_config=None): ''' Get status of running jboss instance. jboss_config Configuration dictionary with properties specified above. host The name of the host. JBoss domain mode only - and required if running in domain mode. The host name is the "name" attribute of the "host" element in host.xml server_config The name of the Server Configuration. JBoss Domain mode only - and required if running in domain mode. CLI Example: .. code-block:: bash salt '*' jboss7.status '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' ''' log.debug("======================== MODULE FUNCTION: jboss7.status") if host is None and server_config is None: operation = ':read-attribute(name=server-state)' elif host is not None and server_config is not None: operation = '/host="{host}"/server-config="{server_config}"/:read-attribute(name=status)'.format( host=host, server_config=server_config) else: raise SaltInvocationError('Invalid parameters. Must either pass both host and server_config or neither') return __salt__['jboss7_cli.run_operation'](jboss_config, operation, fail_on_error=False, retries=0)
python
def status(jboss_config, host=None, server_config=None): ''' Get status of running jboss instance. jboss_config Configuration dictionary with properties specified above. host The name of the host. JBoss domain mode only - and required if running in domain mode. The host name is the "name" attribute of the "host" element in host.xml server_config The name of the Server Configuration. JBoss Domain mode only - and required if running in domain mode. CLI Example: .. code-block:: bash salt '*' jboss7.status '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' ''' log.debug("======================== MODULE FUNCTION: jboss7.status") if host is None and server_config is None: operation = ':read-attribute(name=server-state)' elif host is not None and server_config is not None: operation = '/host="{host}"/server-config="{server_config}"/:read-attribute(name=status)'.format( host=host, server_config=server_config) else: raise SaltInvocationError('Invalid parameters. Must either pass both host and server_config or neither') return __salt__['jboss7_cli.run_operation'](jboss_config, operation, fail_on_error=False, retries=0)
[ "def", "status", "(", "jboss_config", ",", "host", "=", "None", ",", "server_config", "=", "None", ")", ":", "log", ".", "debug", "(", "\"======================== MODULE FUNCTION: jboss7.status\"", ")", "if", "host", "is", "None", "and", "server_config", "is", "...
Get status of running jboss instance. jboss_config Configuration dictionary with properties specified above. host The name of the host. JBoss domain mode only - and required if running in domain mode. The host name is the "name" attribute of the "host" element in host.xml server_config The name of the Server Configuration. JBoss Domain mode only - and required if running in domain mode. CLI Example: .. code-block:: bash salt '*' jboss7.status '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}'
[ "Get", "status", "of", "running", "jboss", "instance", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jboss7.py#L44-L73
train
saltstack/salt
salt/modules/jboss7.py
stop_server
def stop_server(jboss_config, host=None): ''' Stop running jboss instance jboss_config Configuration dictionary with properties specified above. host The name of the host. JBoss domain mode only - and required if running in domain mode. The host name is the "name" attribute of the "host" element in host.xml CLI Example: .. code-block:: bash salt '*' jboss7.stop_server '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' ''' log.debug("======================== MODULE FUNCTION: jboss7.stop_server") if host is None: operation = ':shutdown' else: operation = '/host="{host}"/:shutdown'.format(host=host) shutdown_result = __salt__['jboss7_cli.run_operation'](jboss_config, operation, fail_on_error=False) # JBoss seems to occasionaly close the channel immediately when :shutdown is sent if shutdown_result['success'] or (not shutdown_result['success'] and 'Operation failed: Channel closed' in shutdown_result['stdout']): return shutdown_result else: raise Exception('''Cannot handle error, return code={retcode}, stdout='{stdout}', stderr='{stderr}' '''.format(**shutdown_result))
python
def stop_server(jboss_config, host=None): ''' Stop running jboss instance jboss_config Configuration dictionary with properties specified above. host The name of the host. JBoss domain mode only - and required if running in domain mode. The host name is the "name" attribute of the "host" element in host.xml CLI Example: .. code-block:: bash salt '*' jboss7.stop_server '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' ''' log.debug("======================== MODULE FUNCTION: jboss7.stop_server") if host is None: operation = ':shutdown' else: operation = '/host="{host}"/:shutdown'.format(host=host) shutdown_result = __salt__['jboss7_cli.run_operation'](jboss_config, operation, fail_on_error=False) # JBoss seems to occasionaly close the channel immediately when :shutdown is sent if shutdown_result['success'] or (not shutdown_result['success'] and 'Operation failed: Channel closed' in shutdown_result['stdout']): return shutdown_result else: raise Exception('''Cannot handle error, return code={retcode}, stdout='{stdout}', stderr='{stderr}' '''.format(**shutdown_result))
[ "def", "stop_server", "(", "jboss_config", ",", "host", "=", "None", ")", ":", "log", ".", "debug", "(", "\"======================== MODULE FUNCTION: jboss7.stop_server\"", ")", "if", "host", "is", "None", ":", "operation", "=", "':shutdown'", "else", ":", "operat...
Stop running jboss instance jboss_config Configuration dictionary with properties specified above. host The name of the host. JBoss domain mode only - and required if running in domain mode. The host name is the "name" attribute of the "host" element in host.xml CLI Example: .. code-block:: bash salt '*' jboss7.stop_server '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}'
[ "Stop", "running", "jboss", "instance" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jboss7.py#L76-L103
train
saltstack/salt
salt/modules/jboss7.py
reload_
def reload_(jboss_config, host=None): ''' Reload running jboss instance jboss_config Configuration dictionary with properties specified above. host The name of the host. JBoss domain mode only - and required if running in domain mode. The host name is the "name" attribute of the "host" element in host.xml CLI Example: .. code-block:: bash salt '*' jboss7.reload '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' ''' log.debug("======================== MODULE FUNCTION: jboss7.reload") if host is None: operation = ':reload' else: operation = '/host="{host}"/:reload'.format(host=host) reload_result = __salt__['jboss7_cli.run_operation'](jboss_config, operation, fail_on_error=False) # JBoss seems to occasionaly close the channel immediately when :reload is sent if reload_result['success'] or (not reload_result['success'] and ('Operation failed: Channel closed' in reload_result['stdout'] or 'Communication error: java.util.concurrent.ExecutionException: Operation failed' in reload_result['stdout'])): return reload_result else: raise Exception('''Cannot handle error, return code={retcode}, stdout='{stdout}', stderr='{stderr}' '''.format(**reload_result))
python
def reload_(jboss_config, host=None): ''' Reload running jboss instance jboss_config Configuration dictionary with properties specified above. host The name of the host. JBoss domain mode only - and required if running in domain mode. The host name is the "name" attribute of the "host" element in host.xml CLI Example: .. code-block:: bash salt '*' jboss7.reload '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' ''' log.debug("======================== MODULE FUNCTION: jboss7.reload") if host is None: operation = ':reload' else: operation = '/host="{host}"/:reload'.format(host=host) reload_result = __salt__['jboss7_cli.run_operation'](jboss_config, operation, fail_on_error=False) # JBoss seems to occasionaly close the channel immediately when :reload is sent if reload_result['success'] or (not reload_result['success'] and ('Operation failed: Channel closed' in reload_result['stdout'] or 'Communication error: java.util.concurrent.ExecutionException: Operation failed' in reload_result['stdout'])): return reload_result else: raise Exception('''Cannot handle error, return code={retcode}, stdout='{stdout}', stderr='{stderr}' '''.format(**reload_result))
[ "def", "reload_", "(", "jboss_config", ",", "host", "=", "None", ")", ":", "log", ".", "debug", "(", "\"======================== MODULE FUNCTION: jboss7.reload\"", ")", "if", "host", "is", "None", ":", "operation", "=", "':reload'", "else", ":", "operation", "="...
Reload running jboss instance jboss_config Configuration dictionary with properties specified above. host The name of the host. JBoss domain mode only - and required if running in domain mode. The host name is the "name" attribute of the "host" element in host.xml CLI Example: .. code-block:: bash salt '*' jboss7.reload '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}'
[ "Reload", "running", "jboss", "instance" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jboss7.py#L106-L135
train
saltstack/salt
salt/modules/jboss7.py
create_datasource
def create_datasource(jboss_config, name, datasource_properties, profile=None): ''' Create datasource in running jboss instance jboss_config Configuration dictionary with properties specified above. name Datasource name datasource_properties A dictionary of datasource properties to be created: - driver-name: mysql - connection-url: 'jdbc:mysql://localhost:3306/sampleDatabase' - jndi-name: 'java:jboss/datasources/sampleDS' - user-name: sampleuser - password: secret - min-pool-size: 3 - use-java-context: True profile The profile name (JBoss domain mode only) CLI Example: .. code-block:: bash salt '*' jboss7.create_datasource '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' 'my_datasource' '{"driver-name": "mysql", "connection-url": "jdbc:mysql://localhost:3306/sampleDatabase", "jndi-name": "java:jboss/datasources/sampleDS", "user-name": "sampleuser", "password": "secret", "min-pool-size": 3, "use-java-context": True}' ''' log.debug("======================== MODULE FUNCTION: jboss7.create_datasource, name=%s, profile=%s", name, profile) ds_resource_description = __get_datasource_resource_description(jboss_config, name, profile) operation = '/subsystem=datasources/data-source="{name}":add({properties})'.format( name=name, properties=__get_properties_assignment_string(datasource_properties, ds_resource_description) ) if profile is not None: operation = '/profile="{profile}"'.format(profile=profile) + operation return __salt__['jboss7_cli.run_operation'](jboss_config, operation, fail_on_error=False)
python
def create_datasource(jboss_config, name, datasource_properties, profile=None): ''' Create datasource in running jboss instance jboss_config Configuration dictionary with properties specified above. name Datasource name datasource_properties A dictionary of datasource properties to be created: - driver-name: mysql - connection-url: 'jdbc:mysql://localhost:3306/sampleDatabase' - jndi-name: 'java:jboss/datasources/sampleDS' - user-name: sampleuser - password: secret - min-pool-size: 3 - use-java-context: True profile The profile name (JBoss domain mode only) CLI Example: .. code-block:: bash salt '*' jboss7.create_datasource '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' 'my_datasource' '{"driver-name": "mysql", "connection-url": "jdbc:mysql://localhost:3306/sampleDatabase", "jndi-name": "java:jboss/datasources/sampleDS", "user-name": "sampleuser", "password": "secret", "min-pool-size": 3, "use-java-context": True}' ''' log.debug("======================== MODULE FUNCTION: jboss7.create_datasource, name=%s, profile=%s", name, profile) ds_resource_description = __get_datasource_resource_description(jboss_config, name, profile) operation = '/subsystem=datasources/data-source="{name}":add({properties})'.format( name=name, properties=__get_properties_assignment_string(datasource_properties, ds_resource_description) ) if profile is not None: operation = '/profile="{profile}"'.format(profile=profile) + operation return __salt__['jboss7_cli.run_operation'](jboss_config, operation, fail_on_error=False)
[ "def", "create_datasource", "(", "jboss_config", ",", "name", ",", "datasource_properties", ",", "profile", "=", "None", ")", ":", "log", ".", "debug", "(", "\"======================== MODULE FUNCTION: jboss7.create_datasource, name=%s, profile=%s\"", ",", "name", ",", "p...
Create datasource in running jboss instance jboss_config Configuration dictionary with properties specified above. name Datasource name datasource_properties A dictionary of datasource properties to be created: - driver-name: mysql - connection-url: 'jdbc:mysql://localhost:3306/sampleDatabase' - jndi-name: 'java:jboss/datasources/sampleDS' - user-name: sampleuser - password: secret - min-pool-size: 3 - use-java-context: True profile The profile name (JBoss domain mode only) CLI Example: .. code-block:: bash salt '*' jboss7.create_datasource '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' 'my_datasource' '{"driver-name": "mysql", "connection-url": "jdbc:mysql://localhost:3306/sampleDatabase", "jndi-name": "java:jboss/datasources/sampleDS", "user-name": "sampleuser", "password": "secret", "min-pool-size": 3, "use-java-context": True}'
[ "Create", "datasource", "in", "running", "jboss", "instance" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jboss7.py#L138-L174
train
saltstack/salt
salt/modules/jboss7.py
update_datasource
def update_datasource(jboss_config, name, new_properties, profile=None): ''' Update an existing datasource in running jboss instance. If the property doesn't exist if will be created, if it does, it will be updated with the new value jboss_config Configuration dictionary with properties specified above. name Datasource name new_properties A dictionary of datasource properties to be updated. For example: - driver-name: mysql - connection-url: 'jdbc:mysql://localhost:3306/sampleDatabase' - jndi-name: 'java:jboss/datasources/sampleDS' - user-name: sampleuser - password: secret - min-pool-size: 3 - use-java-context: True profile The profile name (JBoss domain mode only) CLI Example: .. code-block:: bash salt '*' jboss7.update_datasource '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' 'my_datasource' '{"driver-name": "mysql", "connection-url": "jdbc:mysql://localhost:3306/sampleDatabase", "jndi-name": "java:jboss/datasources/sampleDS", "user-name": "sampleuser", "password": "secret", "min-pool-size": 3, "use-java-context": True}' ''' log.debug("======================== MODULE FUNCTION: jboss7.update_datasource, name=%s, profile=%s", name, profile) ds_result = __read_datasource(jboss_config, name, profile) current_properties = ds_result['result'] diff = dictdiffer.DictDiffer(new_properties, current_properties) changed_properties = diff.changed() ret = { 'success': True, 'comment': '' } if changed_properties: ds_resource_description = __get_datasource_resource_description(jboss_config, name, profile) ds_attributes = ds_resource_description['attributes'] for key in changed_properties: update_result = __update_datasource_property(jboss_config, name, key, new_properties[key], ds_attributes, profile) if not update_result['success']: ret['result'] = False ret['comment'] = ret['comment'] + ('Could not update datasource property {0} with value {1},\n stdout: {2}\n'.format(key, new_properties[key], update_result['stdout'])) return ret
python
def update_datasource(jboss_config, name, new_properties, profile=None): ''' Update an existing datasource in running jboss instance. If the property doesn't exist if will be created, if it does, it will be updated with the new value jboss_config Configuration dictionary with properties specified above. name Datasource name new_properties A dictionary of datasource properties to be updated. For example: - driver-name: mysql - connection-url: 'jdbc:mysql://localhost:3306/sampleDatabase' - jndi-name: 'java:jboss/datasources/sampleDS' - user-name: sampleuser - password: secret - min-pool-size: 3 - use-java-context: True profile The profile name (JBoss domain mode only) CLI Example: .. code-block:: bash salt '*' jboss7.update_datasource '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' 'my_datasource' '{"driver-name": "mysql", "connection-url": "jdbc:mysql://localhost:3306/sampleDatabase", "jndi-name": "java:jboss/datasources/sampleDS", "user-name": "sampleuser", "password": "secret", "min-pool-size": 3, "use-java-context": True}' ''' log.debug("======================== MODULE FUNCTION: jboss7.update_datasource, name=%s, profile=%s", name, profile) ds_result = __read_datasource(jboss_config, name, profile) current_properties = ds_result['result'] diff = dictdiffer.DictDiffer(new_properties, current_properties) changed_properties = diff.changed() ret = { 'success': True, 'comment': '' } if changed_properties: ds_resource_description = __get_datasource_resource_description(jboss_config, name, profile) ds_attributes = ds_resource_description['attributes'] for key in changed_properties: update_result = __update_datasource_property(jboss_config, name, key, new_properties[key], ds_attributes, profile) if not update_result['success']: ret['result'] = False ret['comment'] = ret['comment'] + ('Could not update datasource property {0} with value {1},\n stdout: {2}\n'.format(key, new_properties[key], update_result['stdout'])) return ret
[ "def", "update_datasource", "(", "jboss_config", ",", "name", ",", "new_properties", ",", "profile", "=", "None", ")", ":", "log", ".", "debug", "(", "\"======================== MODULE FUNCTION: jboss7.update_datasource, name=%s, profile=%s\"", ",", "name", ",", "profile"...
Update an existing datasource in running jboss instance. If the property doesn't exist if will be created, if it does, it will be updated with the new value jboss_config Configuration dictionary with properties specified above. name Datasource name new_properties A dictionary of datasource properties to be updated. For example: - driver-name: mysql - connection-url: 'jdbc:mysql://localhost:3306/sampleDatabase' - jndi-name: 'java:jboss/datasources/sampleDS' - user-name: sampleuser - password: secret - min-pool-size: 3 - use-java-context: True profile The profile name (JBoss domain mode only) CLI Example: .. code-block:: bash salt '*' jboss7.update_datasource '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' 'my_datasource' '{"driver-name": "mysql", "connection-url": "jdbc:mysql://localhost:3306/sampleDatabase", "jndi-name": "java:jboss/datasources/sampleDS", "user-name": "sampleuser", "password": "secret", "min-pool-size": 3, "use-java-context": True}'
[ "Update", "an", "existing", "datasource", "in", "running", "jboss", "instance", ".", "If", "the", "property", "doesn", "t", "exist", "if", "will", "be", "created", "if", "it", "does", "it", "will", "be", "updated", "with", "the", "new", "value" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jboss7.py#L211-L258
train
saltstack/salt
salt/modules/jboss7.py
read_datasource
def read_datasource(jboss_config, name, profile=None): ''' Read datasource properties in the running jboss instance. jboss_config Configuration dictionary with properties specified above. name Datasource name profile Profile name (JBoss domain mode only) CLI Example: .. code-block:: bash salt '*' jboss7.read_datasource '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' ''' log.debug("======================== MODULE FUNCTION: jboss7.read_datasource, name=%s", name) return __read_datasource(jboss_config, name, profile)
python
def read_datasource(jboss_config, name, profile=None): ''' Read datasource properties in the running jboss instance. jboss_config Configuration dictionary with properties specified above. name Datasource name profile Profile name (JBoss domain mode only) CLI Example: .. code-block:: bash salt '*' jboss7.read_datasource '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' ''' log.debug("======================== MODULE FUNCTION: jboss7.read_datasource, name=%s", name) return __read_datasource(jboss_config, name, profile)
[ "def", "read_datasource", "(", "jboss_config", ",", "name", ",", "profile", "=", "None", ")", ":", "log", ".", "debug", "(", "\"======================== MODULE FUNCTION: jboss7.read_datasource, name=%s\"", ",", "name", ")", "return", "__read_datasource", "(", "jboss_con...
Read datasource properties in the running jboss instance. jboss_config Configuration dictionary with properties specified above. name Datasource name profile Profile name (JBoss domain mode only) CLI Example: .. code-block:: bash salt '*' jboss7.read_datasource '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}'
[ "Read", "datasource", "properties", "in", "the", "running", "jboss", "instance", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jboss7.py#L272-L290
train
saltstack/salt
salt/modules/jboss7.py
create_simple_binding
def create_simple_binding(jboss_config, binding_name, value, profile=None): ''' Create a simple jndi binding in the running jboss instance jboss_config Configuration dictionary with properties specified above. binding_name Binding name to be created value Binding value profile The profile name (JBoss domain mode only) CLI Example: .. code-block:: bash salt '*' jboss7.create_simple_binding \\ '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", \\ "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' \\ my_binding_name my_binding_value ''' log.debug("======================== MODULE FUNCTION: jboss7.create_simple_binding, binding_name=%s, value=%s, profile=%s", binding_name, value, profile) operation = '/subsystem=naming/binding="{binding_name}":add(binding-type=simple, value="{value}")'.format( binding_name=binding_name, value=__escape_binding_value(value) ) if profile is not None: operation = '/profile="{profile}"'.format(profile=profile) + operation return __salt__['jboss7_cli.run_operation'](jboss_config, operation)
python
def create_simple_binding(jboss_config, binding_name, value, profile=None): ''' Create a simple jndi binding in the running jboss instance jboss_config Configuration dictionary with properties specified above. binding_name Binding name to be created value Binding value profile The profile name (JBoss domain mode only) CLI Example: .. code-block:: bash salt '*' jboss7.create_simple_binding \\ '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", \\ "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' \\ my_binding_name my_binding_value ''' log.debug("======================== MODULE FUNCTION: jboss7.create_simple_binding, binding_name=%s, value=%s, profile=%s", binding_name, value, profile) operation = '/subsystem=naming/binding="{binding_name}":add(binding-type=simple, value="{value}")'.format( binding_name=binding_name, value=__escape_binding_value(value) ) if profile is not None: operation = '/profile="{profile}"'.format(profile=profile) + operation return __salt__['jboss7_cli.run_operation'](jboss_config, operation)
[ "def", "create_simple_binding", "(", "jboss_config", ",", "binding_name", ",", "value", ",", "profile", "=", "None", ")", ":", "log", ".", "debug", "(", "\"======================== MODULE FUNCTION: jboss7.create_simple_binding, binding_name=%s, value=%s, profile=%s\"", ",", "...
Create a simple jndi binding in the running jboss instance jboss_config Configuration dictionary with properties specified above. binding_name Binding name to be created value Binding value profile The profile name (JBoss domain mode only) CLI Example: .. code-block:: bash salt '*' jboss7.create_simple_binding \\ '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", \\ "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' \\ my_binding_name my_binding_value
[ "Create", "a", "simple", "jndi", "binding", "in", "the", "running", "jboss", "instance" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jboss7.py#L293-L322
train
saltstack/salt
salt/modules/jboss7.py
read_simple_binding
def read_simple_binding(jboss_config, binding_name, profile=None): ''' Read jndi binding in the running jboss instance jboss_config Configuration dictionary with properties specified above. binding_name Binding name to be created profile The profile name (JBoss domain mode only) CLI Example: .. code-block:: bash salt '*' jboss7.read_simple_binding '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' my_binding_name ''' log.debug("======================== MODULE FUNCTION: jboss7.read_simple_binding, %s", binding_name) return __read_simple_binding(jboss_config, binding_name, profile=profile)
python
def read_simple_binding(jboss_config, binding_name, profile=None): ''' Read jndi binding in the running jboss instance jboss_config Configuration dictionary with properties specified above. binding_name Binding name to be created profile The profile name (JBoss domain mode only) CLI Example: .. code-block:: bash salt '*' jboss7.read_simple_binding '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' my_binding_name ''' log.debug("======================== MODULE FUNCTION: jboss7.read_simple_binding, %s", binding_name) return __read_simple_binding(jboss_config, binding_name, profile=profile)
[ "def", "read_simple_binding", "(", "jboss_config", ",", "binding_name", ",", "profile", "=", "None", ")", ":", "log", ".", "debug", "(", "\"======================== MODULE FUNCTION: jboss7.read_simple_binding, %s\"", ",", "binding_name", ")", "return", "__read_simple_bindin...
Read jndi binding in the running jboss instance jboss_config Configuration dictionary with properties specified above. binding_name Binding name to be created profile The profile name (JBoss domain mode only) CLI Example: .. code-block:: bash salt '*' jboss7.read_simple_binding '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' my_binding_name
[ "Read", "jndi", "binding", "in", "the", "running", "jboss", "instance" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jboss7.py#L354-L372
train
saltstack/salt
salt/modules/jboss7.py
remove_datasource
def remove_datasource(jboss_config, name, profile=None): ''' Remove an existing datasource from the running jboss instance. jboss_config Configuration dictionary with properties specified above. name Datasource name profile The profile (JBoss domain mode only) CLI Example: .. code-block:: bash salt '*' jboss7.remove_datasource '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' my_datasource_name ''' log.debug("======================== MODULE FUNCTION: jboss7.remove_datasource, name=%s, profile=%s", name, profile) operation = '/subsystem=datasources/data-source={name}:remove'.format(name=name) if profile is not None: operation = '/profile="{profile}"'.format(profile=profile) + operation return __salt__['jboss7_cli.run_operation'](jboss_config, operation, fail_on_error=False)
python
def remove_datasource(jboss_config, name, profile=None): ''' Remove an existing datasource from the running jboss instance. jboss_config Configuration dictionary with properties specified above. name Datasource name profile The profile (JBoss domain mode only) CLI Example: .. code-block:: bash salt '*' jboss7.remove_datasource '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' my_datasource_name ''' log.debug("======================== MODULE FUNCTION: jboss7.remove_datasource, name=%s, profile=%s", name, profile) operation = '/subsystem=datasources/data-source={name}:remove'.format(name=name) if profile is not None: operation = '/profile="{profile}"'.format(profile=profile) + operation return __salt__['jboss7_cli.run_operation'](jboss_config, operation, fail_on_error=False)
[ "def", "remove_datasource", "(", "jboss_config", ",", "name", ",", "profile", "=", "None", ")", ":", "log", ".", "debug", "(", "\"======================== MODULE FUNCTION: jboss7.remove_datasource, name=%s, profile=%s\"", ",", "name", ",", "profile", ")", "operation", "...
Remove an existing datasource from the running jboss instance. jboss_config Configuration dictionary with properties specified above. name Datasource name profile The profile (JBoss domain mode only) CLI Example: .. code-block:: bash salt '*' jboss7.remove_datasource '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' my_datasource_name
[ "Remove", "an", "existing", "datasource", "from", "the", "running", "jboss", "instance", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jboss7.py#L414-L437
train
saltstack/salt
salt/modules/jboss7.py
deploy
def deploy(jboss_config, source_file): ''' Deploy the application on the jboss instance from the local file system where minion is running. jboss_config Configuration dictionary with properties specified above. source_file Source file to deploy from CLI Example: .. code-block:: bash salt '*' jboss7.deploy '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' /opt/deploy_files/my_deploy ''' log.debug("======================== MODULE FUNCTION: jboss7.deploy, source_file=%s", source_file) command = 'deploy {source_file} --force '.format(source_file=source_file) return __salt__['jboss7_cli.run_command'](jboss_config, command, fail_on_error=False)
python
def deploy(jboss_config, source_file): ''' Deploy the application on the jboss instance from the local file system where minion is running. jboss_config Configuration dictionary with properties specified above. source_file Source file to deploy from CLI Example: .. code-block:: bash salt '*' jboss7.deploy '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' /opt/deploy_files/my_deploy ''' log.debug("======================== MODULE FUNCTION: jboss7.deploy, source_file=%s", source_file) command = 'deploy {source_file} --force '.format(source_file=source_file) return __salt__['jboss7_cli.run_command'](jboss_config, command, fail_on_error=False)
[ "def", "deploy", "(", "jboss_config", ",", "source_file", ")", ":", "log", ".", "debug", "(", "\"======================== MODULE FUNCTION: jboss7.deploy, source_file=%s\"", ",", "source_file", ")", "command", "=", "'deploy {source_file} --force '", ".", "format", "(", "so...
Deploy the application on the jboss instance from the local file system where minion is running. jboss_config Configuration dictionary with properties specified above. source_file Source file to deploy from CLI Example: .. code-block:: bash salt '*' jboss7.deploy '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' /opt/deploy_files/my_deploy
[ "Deploy", "the", "application", "on", "the", "jboss", "instance", "from", "the", "local", "file", "system", "where", "minion", "is", "running", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jboss7.py#L440-L457
train
saltstack/salt
salt/modules/jboss7.py
list_deployments
def list_deployments(jboss_config): ''' List all deployments on the jboss instance jboss_config Configuration dictionary with properties specified above. CLI Example: .. code-block:: bash salt '*' jboss7.list_deployments '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' ''' log.debug("======================== MODULE FUNCTION: jboss7.list_deployments") command_result = __salt__['jboss7_cli.run_command'](jboss_config, 'deploy') deployments = [] if command_result['stdout']: deployments = re.split('\\s*', command_result['stdout']) log.debug('deployments=%s', deployments) return deployments
python
def list_deployments(jboss_config): ''' List all deployments on the jboss instance jboss_config Configuration dictionary with properties specified above. CLI Example: .. code-block:: bash salt '*' jboss7.list_deployments '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' ''' log.debug("======================== MODULE FUNCTION: jboss7.list_deployments") command_result = __salt__['jboss7_cli.run_command'](jboss_config, 'deploy') deployments = [] if command_result['stdout']: deployments = re.split('\\s*', command_result['stdout']) log.debug('deployments=%s', deployments) return deployments
[ "def", "list_deployments", "(", "jboss_config", ")", ":", "log", ".", "debug", "(", "\"======================== MODULE FUNCTION: jboss7.list_deployments\"", ")", "command_result", "=", "__salt__", "[", "'jboss7_cli.run_command'", "]", "(", "jboss_config", ",", "'deploy'", ...
List all deployments on the jboss instance jboss_config Configuration dictionary with properties specified above. CLI Example: .. code-block:: bash salt '*' jboss7.list_deployments '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}'
[ "List", "all", "deployments", "on", "the", "jboss", "instance" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jboss7.py#L460-L480
train
saltstack/salt
salt/modules/jboss7.py
undeploy
def undeploy(jboss_config, deployment): ''' Undeploy the application from jboss instance jboss_config Configuration dictionary with properties specified above. deployment Deployment name to undeploy CLI Example: .. code-block:: bash salt '*' jboss7.undeploy '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' my_deployment ''' log.debug("======================== MODULE FUNCTION: jboss7.undeploy, deployment=%s", deployment) command = 'undeploy {deployment} '.format(deployment=deployment) return __salt__['jboss7_cli.run_command'](jboss_config, command)
python
def undeploy(jboss_config, deployment): ''' Undeploy the application from jboss instance jboss_config Configuration dictionary with properties specified above. deployment Deployment name to undeploy CLI Example: .. code-block:: bash salt '*' jboss7.undeploy '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' my_deployment ''' log.debug("======================== MODULE FUNCTION: jboss7.undeploy, deployment=%s", deployment) command = 'undeploy {deployment} '.format(deployment=deployment) return __salt__['jboss7_cli.run_command'](jboss_config, command)
[ "def", "undeploy", "(", "jboss_config", ",", "deployment", ")", ":", "log", ".", "debug", "(", "\"======================== MODULE FUNCTION: jboss7.undeploy, deployment=%s\"", ",", "deployment", ")", "command", "=", "'undeploy {deployment} '", ".", "format", "(", "deployme...
Undeploy the application from jboss instance jboss_config Configuration dictionary with properties specified above. deployment Deployment name to undeploy CLI Example: .. code-block:: bash salt '*' jboss7.undeploy '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' my_deployment
[ "Undeploy", "the", "application", "from", "jboss", "instance" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jboss7.py#L483-L500
train
saltstack/salt
salt/utils/timeutil.py
get_timestamp_at
def get_timestamp_at(time_in=None, time_at=None): ''' Computes the timestamp for a future event that may occur in ``time_in`` time or at ``time_at``. ''' if time_in: if isinstance(time_in, int): hours = 0 minutes = time_in else: time_in = time_in.replace('h', ':') time_in = time_in.replace('m', '') try: hours, minutes = time_in.split(':') except ValueError: hours = 0 minutes = time_in if not minutes: minutes = 0 hours, minutes = int(hours), int(minutes) dt = timedelta(hours=hours, minutes=minutes) time_now = datetime.utcnow() time_at = time_now + dt return time.mktime(time_at.timetuple()) elif time_at: log.debug('Predicted at specified as %s', time_at) if isinstance(time_at, (six.integer_types, float)): # then it's a timestamp return time_at else: fmts = ('%H%M', '%Hh%M', '%I%p', '%I:%M%p', '%I:%M %p') # Support different formats for the timestamp # The current formats accepted are the following: # # - 18:30 (and 18h30) # - 1pm (no minutes, fixed hour) # - 1:20am (and 1:20am - with or without space) for fmt in fmts: try: log.debug('Trying to match %s', fmt) dt = datetime.strptime(time_at, fmt) return time.mktime(dt.timetuple()) except ValueError: log.debug('Did not match %s, continue searching', fmt) continue msg = '{pat} does not match any of the accepted formats: {fmts}'.format(pat=time_at, fmts=', '.join(fmts)) log.error(msg) raise ValueError(msg)
python
def get_timestamp_at(time_in=None, time_at=None): ''' Computes the timestamp for a future event that may occur in ``time_in`` time or at ``time_at``. ''' if time_in: if isinstance(time_in, int): hours = 0 minutes = time_in else: time_in = time_in.replace('h', ':') time_in = time_in.replace('m', '') try: hours, minutes = time_in.split(':') except ValueError: hours = 0 minutes = time_in if not minutes: minutes = 0 hours, minutes = int(hours), int(minutes) dt = timedelta(hours=hours, minutes=minutes) time_now = datetime.utcnow() time_at = time_now + dt return time.mktime(time_at.timetuple()) elif time_at: log.debug('Predicted at specified as %s', time_at) if isinstance(time_at, (six.integer_types, float)): # then it's a timestamp return time_at else: fmts = ('%H%M', '%Hh%M', '%I%p', '%I:%M%p', '%I:%M %p') # Support different formats for the timestamp # The current formats accepted are the following: # # - 18:30 (and 18h30) # - 1pm (no minutes, fixed hour) # - 1:20am (and 1:20am - with or without space) for fmt in fmts: try: log.debug('Trying to match %s', fmt) dt = datetime.strptime(time_at, fmt) return time.mktime(dt.timetuple()) except ValueError: log.debug('Did not match %s, continue searching', fmt) continue msg = '{pat} does not match any of the accepted formats: {fmts}'.format(pat=time_at, fmts=', '.join(fmts)) log.error(msg) raise ValueError(msg)
[ "def", "get_timestamp_at", "(", "time_in", "=", "None", ",", "time_at", "=", "None", ")", ":", "if", "time_in", ":", "if", "isinstance", "(", "time_in", ",", "int", ")", ":", "hours", "=", "0", "minutes", "=", "time_in", "else", ":", "time_in", "=", ...
Computes the timestamp for a future event that may occur in ``time_in`` time or at ``time_at``.
[ "Computes", "the", "timestamp", "for", "a", "future", "event", "that", "may", "occur", "in", "time_in", "time", "or", "at", "time_at", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/timeutil.py#L18-L66
train
saltstack/salt
salt/utils/timeutil.py
get_time_at
def get_time_at(time_in=None, time_at=None, out_fmt='%Y-%m-%dT%H:%M:%S'): ''' Return the time in human readable format for a future event that may occur in ``time_in`` time, or at ``time_at``. ''' dt = get_timestamp_at(time_in=time_in, time_at=time_at) return time.strftime(out_fmt, time.localtime(dt))
python
def get_time_at(time_in=None, time_at=None, out_fmt='%Y-%m-%dT%H:%M:%S'): ''' Return the time in human readable format for a future event that may occur in ``time_in`` time, or at ``time_at``. ''' dt = get_timestamp_at(time_in=time_in, time_at=time_at) return time.strftime(out_fmt, time.localtime(dt))
[ "def", "get_time_at", "(", "time_in", "=", "None", ",", "time_at", "=", "None", ",", "out_fmt", "=", "'%Y-%m-%dT%H:%M:%S'", ")", ":", "dt", "=", "get_timestamp_at", "(", "time_in", "=", "time_in", ",", "time_at", "=", "time_at", ")", "return", "time", ".",...
Return the time in human readable format for a future event that may occur in ``time_in`` time, or at ``time_at``.
[ "Return", "the", "time", "in", "human", "readable", "format", "for", "a", "future", "event", "that", "may", "occur", "in", "time_in", "time", "or", "at", "time_at", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/timeutil.py#L69-L75
train
saltstack/salt
salt/states/archive.py
_path_is_abs
def _path_is_abs(path): ''' Return a bool telling whether or ``path`` is absolute. If ``path`` is None, return ``True``. This function is designed to validate variables which optionally contain a file path. ''' if path is None: return True try: return os.path.isabs(path) except AttributeError: # Non-string data passed return False
python
def _path_is_abs(path): ''' Return a bool telling whether or ``path`` is absolute. If ``path`` is None, return ``True``. This function is designed to validate variables which optionally contain a file path. ''' if path is None: return True try: return os.path.isabs(path) except AttributeError: # Non-string data passed return False
[ "def", "_path_is_abs", "(", "path", ")", ":", "if", "path", "is", "None", ":", "return", "True", "try", ":", "return", "os", ".", "path", ".", "isabs", "(", "path", ")", "except", "AttributeError", ":", "# Non-string data passed", "return", "False" ]
Return a bool telling whether or ``path`` is absolute. If ``path`` is None, return ``True``. This function is designed to validate variables which optionally contain a file path.
[ "Return", "a", "bool", "telling", "whether", "or", "path", "is", "absolute", ".", "If", "path", "is", "None", "return", "True", ".", "This", "function", "is", "designed", "to", "validate", "variables", "which", "optionally", "contain", "a", "file", "path", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/archive.py#L37-L49
train
saltstack/salt
salt/states/archive.py
extracted
def extracted(name, source, source_hash=None, source_hash_name=None, source_hash_update=False, skip_verify=False, password=None, options=None, list_options=None, force=False, overwrite=False, clean=False, user=None, group=None, if_missing=None, trim_output=False, use_cmd_unzip=None, extract_perms=True, enforce_toplevel=True, enforce_ownership_on=None, archive_format=None, **kwargs): ''' .. versionadded:: 2014.1.0 .. versionchanged:: 2016.11.0 This state has been rewritten. Some arguments are new to this release and will not be available in the 2016.3 release cycle (and earlier). Additionally, the **ZIP Archive Handling** section below applies specifically to the 2016.11.0 release (and newer). Ensure that an archive is extracted to a specific directory. .. important:: **Changes for 2016.11.0** In earlier releases, this state would rely on the ``if_missing`` argument to determine whether or not the archive needed to be extracted. When this argument was not passed, then the state would just assume ``if_missing`` is the same as the ``name`` argument (i.e. the parent directory into which the archive would be extracted). This caused a number of annoyances. One such annoyance was the need to know beforehand a path that would result from the extraction of the archive, and setting ``if_missing`` to that directory, like so: .. code-block:: yaml extract_myapp: archive.extracted: - name: /var/www - source: salt://apps/src/myapp-16.2.4.tar.gz - user: www - group: www - if_missing: /var/www/myapp-16.2.4 If ``/var/www`` already existed, this would effectively make ``if_missing`` a required argument, just to get Salt to extract the archive. Some users worked around this by adding the top-level directory of the archive to the end of the ``name`` argument, and then used ``--strip`` or ``--strip-components`` to remove that top-level dir when extracting: .. code-block:: yaml extract_myapp: archive.extracted: - name: /var/www/myapp-16.2.4 - source: salt://apps/src/myapp-16.2.4.tar.gz - user: www - group: www With the rewrite for 2016.11.0, these workarounds are no longer necessary. ``if_missing`` is still a supported argument, but it is no longer required. The equivalent SLS in 2016.11.0 would be: .. code-block:: yaml extract_myapp: archive.extracted: - name: /var/www - source: salt://apps/src/myapp-16.2.4.tar.gz - user: www - group: www Salt now uses a function called :py:func:`archive.list <salt.modules.archive.list>` to get a list of files/directories in the archive. Using this information, the state can now check the minion to see if any paths are missing, and know whether or not the archive needs to be extracted. This makes the ``if_missing`` argument unnecessary in most use cases. .. important:: **ZIP Archive Handling** *Note: this information applies to 2016.11.0 and later.* Salt has two different functions for extracting ZIP archives: 1. :py:func:`archive.unzip <salt.modules.archive.unzip>`, which uses Python's zipfile_ module to extract ZIP files. 2. :py:func:`archive.cmd_unzip <salt.modules.archive.cmd_unzip>`, which uses the ``unzip`` CLI command to extract ZIP files. Salt will prefer the use of :py:func:`archive.cmd_unzip <salt.modules.archive.cmd_unzip>` when CLI options are specified (via the ``options`` argument), and will otherwise prefer the :py:func:`archive.unzip <salt.modules.archive.unzip>` function. Use of :py:func:`archive.cmd_unzip <salt.modules.archive.cmd_unzip>` can be forced however by setting the ``use_cmd_unzip`` argument to ``True``. By contrast, setting this argument to ``False`` will force usage of :py:func:`archive.unzip <salt.modules.archive.unzip>`. For example: .. code-block:: yaml /var/www: archive.extracted: - source: salt://foo/bar/myapp.zip - use_cmd_unzip: True When ``use_cmd_unzip`` is omitted, Salt will choose which extraction function to use based on the source archive and the arguments passed to the state. When in doubt, simply do not set this argument; it is provided as a means of overriding the logic Salt uses to decide which function to use. There are differences in the features available in both extraction functions. These are detailed below. - *Command-line options* (only supported by :py:func:`archive.cmd_unzip <salt.modules.archive.cmd_unzip>`) - When the ``options`` argument is used, :py:func:`archive.cmd_unzip <salt.modules.archive.cmd_unzip>` is the only function that can be used to extract the archive. Therefore, if ``use_cmd_unzip`` is specified and set to ``False``, and ``options`` is also set, the state will not proceed. - *Permissions* - Due to an `upstream bug in Python`_, permissions are not preserved when the zipfile_ module is used to extract an archive. As of the 2016.11.0 release, :py:func:`archive.unzip <salt.modules.archive.unzip>` (as well as this state) has an ``extract_perms`` argument which, when set to ``True`` (the default), will attempt to match the permissions of the extracted files/directories to those defined within the archive. To disable this functionality and have the state not attempt to preserve the permissions from the ZIP archive, set ``extract_perms`` to ``False``: .. code-block:: yaml /var/www: archive.extracted: - source: salt://foo/bar/myapp.zip - extract_perms: False .. _`upstream bug in Python`: https://bugs.python.org/issue15795 name Directory into which the archive should be extracted source Archive to be extracted .. note:: This argument uses the same syntax as its counterpart in the :py:func:`file.managed <salt.states.file.managed>` state. source_hash Hash of source file, or file with list of hash-to-file mappings .. note:: This argument uses the same syntax as its counterpart in the :py:func:`file.managed <salt.states.file.managed>` state. .. versionchanged:: 2016.11.0 If this argument specifies the hash itself, instead of a URI to a file containing hashes, the hash type can now be omitted and Salt will determine the hash type based on the length of the hash. For example, both of the below states are now valid, while before only the second one would be: .. code-block:: yaml foo_app: archive.extracted: - name: /var/www - source: https://mydomain.tld/foo.tar.gz - source_hash: 3360db35e682f1c5f9c58aa307de16d41361618c bar_app: archive.extracted: - name: /var/www - source: https://mydomain.tld/bar.tar.gz - source_hash: sha1=5edb7d584b82ddcbf76e311601f5d4442974aaa5 source_hash_name When ``source_hash`` refers to a hash file, Salt will try to find the correct hash by matching the filename part of the ``source`` URI. When managing a file with a ``source`` of ``salt://files/foo.tar.gz``, then the following line in a hash file would match: .. code-block:: text acbd18db4cc2f85cedef654fccc4a4d8 foo.tar.gz This line would also match: .. code-block:: text acbd18db4cc2f85cedef654fccc4a4d8 ./dir1/foo.tar.gz However, sometimes a hash file will include multiple similar paths: .. code-block:: text 37b51d194a7513e45b56f6524f2d51f2 ./dir1/foo.txt acbd18db4cc2f85cedef654fccc4a4d8 ./dir2/foo.txt 73feffa4b7f6bb68e44cf984c85f6e88 ./dir3/foo.txt In cases like this, Salt may match the incorrect hash. This argument can be used to tell Salt which filename to match, to ensure that the correct hash is identified. For example: .. code-block:: yaml /var/www: archive.extracted: - source: https://mydomain.tld/dir2/foo.tar.gz - source_hash: https://mydomain.tld/hashes - source_hash_name: ./dir2/foo.tar.gz .. note:: This argument must contain the full filename entry from the checksum file, as this argument is meant to disambiguate matches for multiple files that have the same basename. So, in the example above, simply using ``foo.txt`` would not match. .. versionadded:: 2016.11.0 source_hash_update : False Set this to ``True`` if archive should be extracted if source_hash has changed. This would extract regardless of the ``if_missing`` parameter. Note that this is only checked if the ``source`` value has not changed. If it has (e.g. to increment a version number in the path) then the archive will not be extracted even if the hash has changed. .. versionadded:: 2016.3.0 skip_verify : False If ``True``, hash verification of remote file sources (``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored. .. versionadded:: 2016.3.4 keep_source : True For ``source`` archives not local to the minion (i.e. from the Salt fileserver or a remote source such as ``http(s)`` or ``ftp``), Salt will need to download the archive to the minion cache before they can be extracted. To remove the downloaded archive after extraction, set this argument to ``False``. .. versionadded:: 2017.7.3 keep : True Same as ``keep_source``, kept for backward-compatibility. .. note:: If both ``keep_source`` and ``keep`` are used, ``keep`` will be ignored. password **For ZIP archives only.** Password used for extraction. .. versionadded:: 2016.3.0 .. versionchanged:: 2016.11.0 The newly-added :py:func:`archive.is_encrypted <salt.modules.archive.is_encrypted>` function will be used to determine if the archive is password-protected. If it is, then the ``password`` argument will be required for the state to proceed. options **For tar and zip archives only.** This option can be used to specify a string of additional arguments to pass to the tar/zip command. If this argument is not used, then the minion will attempt to use Python's native tarfile_/zipfile_ support to extract it. For zip archives, this argument is mostly used to overwrite existing files with ``o``. Using this argument means that the ``tar`` or ``unzip`` command will be used, which is less platform-independent, so keep this in mind when using this option; the CLI options must be valid options for the ``tar``/``unzip`` implementation on the minion's OS. .. versionadded:: 2016.11.0 .. versionchanged:: 2015.8.11,2016.3.2 XZ-compressed tar archives no longer require ``J`` to manually be set in the ``options``, they are now detected automatically and decompressed using the xz_ CLI command and extracted using ``tar xvf``. This is a more platform-independent solution, as not all tar implementations support the ``J`` argument for extracting archives. .. note:: For tar archives, main operators like ``-x``, ``--extract``, ``--get``, ``-c`` and ``-f``/``--file`` should *not* be used here. list_options **For tar archives only.** This state uses :py:func:`archive.list <salt.modules.archive.list_>` to discover the contents of the source archive so that it knows which file paths should exist on the minion if the archive has already been extracted. For the vast majority of tar archives, :py:func:`archive.list <salt.modules.archive.list_>` "just works". Archives compressed using gzip, bzip2, and xz/lzma (with the help of the xz_ CLI command) are supported automatically. However, for archives compressed using other compression types, CLI options must be passed to :py:func:`archive.list <salt.modules.archive.list_>`. This argument will be passed through to :py:func:`archive.list <salt.modules.archive.list_>` as its ``options`` argument, to allow it to successfully list the archive's contents. For the vast majority of archives, this argument should not need to be used, it should only be needed in cases where the state fails with an error stating that the archive's contents could not be listed. .. versionadded:: 2016.11.0 force : False If a path that should be occupied by a file in the extracted result is instead a directory (or vice-versa), the state will fail. Set this argument to ``True`` to force these paths to be removed in order to allow the archive to be extracted. .. warning:: Use this option *very* carefully. .. versionadded:: 2016.11.0 overwrite : False Set this to ``True`` to force the archive to be extracted. This is useful for cases where the filenames/directories have not changed, but the content of the files have. .. versionadded:: 2016.11.1 clean : False Set this to ``True`` to remove any top-level files and recursively remove any top-level directory paths before extracting. .. note:: Files will only be cleaned first if extracting the archive is deemed necessary, either by paths missing on the minion, or if ``overwrite`` is set to ``True``. .. versionadded:: 2016.11.1 user The user to own each extracted file. Not available on Windows. .. versionadded:: 2015.8.0 .. versionchanged:: 2016.3.0 When used in combination with ``if_missing``, ownership will only be enforced if ``if_missing`` is a directory. .. versionchanged:: 2016.11.0 Ownership will be enforced only on the file/directory paths found by running :py:func:`archive.list <salt.modules.archive.list_>` on the source archive. An alternative root directory on which to enforce ownership can be specified using the ``enforce_ownership_on`` argument. group The group to own each extracted file. Not available on Windows. .. versionadded:: 2015.8.0 .. versionchanged:: 2016.3.0 When used in combination with ``if_missing``, ownership will only be enforced if ``if_missing`` is a directory. .. versionchanged:: 2016.11.0 Ownership will be enforced only on the file/directory paths found by running :py:func:`archive.list <salt.modules.archive.list_>` on the source archive. An alternative root directory on which to enforce ownership can be specified using the ``enforce_ownership_on`` argument. if_missing If specified, this path will be checked, and if it exists then the archive will not be extracted. This path can be either a directory or a file, so this option can also be used to check for a semaphore file and conditionally skip extraction. .. versionchanged:: 2016.3.0 When used in combination with either ``user`` or ``group``, ownership will only be enforced when ``if_missing`` is a directory. .. versionchanged:: 2016.11.0 Ownership enforcement is no longer tied to this argument, it is simply checked for existence and extraction will be skipped if if is present. trim_output : False Useful for archives with many files in them. This can either be set to ``True`` (in which case only the first 100 files extracted will be in the state results), or it can be set to an integer for more exact control over the max number of files to include in the state results. .. versionadded:: 2016.3.0 use_cmd_unzip : False Set to ``True`` for zip files to force usage of the :py:func:`archive.cmd_unzip <salt.modules.archive.cmd_unzip>` function to extract. .. versionadded:: 2016.11.0 extract_perms : True **For ZIP archives only.** When using :py:func:`archive.unzip <salt.modules.archive.unzip>` to extract ZIP archives, Salt works around an `upstream bug in Python`_ to set the permissions on extracted files/directories to match those encoded into the ZIP archive. Set this argument to ``False`` to skip this workaround. .. versionadded:: 2016.11.0 enforce_toplevel : True This option will enforce a single directory at the top level of the source archive, to prevent extracting a 'tar-bomb'. Set this argument to ``False`` to allow archives with files (or multiple directories) at the top level to be extracted. .. versionadded:: 2016.11.0 enforce_ownership_on When ``user`` or ``group`` is specified, Salt will default to enforcing permissions on the file/directory paths detected by running :py:func:`archive.list <salt.modules.archive.list_>` on the source archive. Use this argument to specify an alternate directory on which ownership should be enforced. .. note:: This path must be within the path specified by the ``name`` argument. .. versionadded:: 2016.11.0 archive_format One of ``tar``, ``zip``, or ``rar``. .. versionchanged:: 2016.11.0 If omitted, the archive format will be guessed based on the value of the ``source`` argument. If the minion is running a release older than 2016.11.0, this option is required. .. _tarfile: https://docs.python.org/2/library/tarfile.html .. _zipfile: https://docs.python.org/2/library/zipfile.html .. _xz: http://tukaani.org/xz/ **Examples** 1. tar with lmza (i.e. xz) compression: .. code-block:: yaml graylog2-server: archive.extracted: - name: /opt/ - source: https://github.com/downloads/Graylog2/graylog2-server/graylog2-server-0.9.6p1.tar.lzma - source_hash: md5=499ae16dcae71eeb7c3a30c75ea7a1a6 2. tar archive with flag for verbose output, and enforcement of user/group ownership: .. code-block:: yaml graylog2-server: archive.extracted: - name: /opt/ - source: https://github.com/downloads/Graylog2/graylog2-server/graylog2-server-0.9.6p1.tar.gz - source_hash: md5=499ae16dcae71eeb7c3a30c75ea7a1a6 - options: v - user: foo - group: foo 3. tar archive, with ``source_hash_update`` set to ``True`` to prevent state from attempting extraction unless the ``source_hash`` differs from the previous time the archive was extracted: .. code-block:: yaml graylog2-server: archive.extracted: - name: /opt/ - source: https://github.com/downloads/Graylog2/graylog2-server/graylog2-server-0.9.6p1.tar.lzma - source_hash: md5=499ae16dcae71eeb7c3a30c75ea7a1a6 - source_hash_update: True ''' ret = {'name': name, 'result': False, 'changes': {}, 'comment': ''} # Remove pub kwargs as they're irrelevant here. kwargs = salt.utils.args.clean_kwargs(**kwargs) if 'keep_source' in kwargs and 'keep' in kwargs: ret.setdefault('warnings', []).append( 'Both \'keep_source\' and \'keep\' were used. Since these both ' 'do the same thing, \'keep\' was ignored.' ) keep_source = bool(kwargs.pop('keep_source')) kwargs.pop('keep') elif 'keep_source' in kwargs: keep_source = bool(kwargs.pop('keep_source')) elif 'keep' in kwargs: keep_source = bool(kwargs.pop('keep')) else: # Neither was passed, default is True keep_source = True if not _path_is_abs(name): ret['comment'] = '{0} is not an absolute path'.format(name) return ret else: if not name: # Empty name, like None, '' etc. ret['comment'] = 'Name of the directory path needs to be specified' return ret # os.path.isfile() returns False when there is a trailing slash, hence # our need for first stripping the slash and then adding it back later. # Otherwise, we can't properly check if the extraction location both a) # exists and b) is a file. # # >>> os.path.isfile('/tmp/foo.txt') # True # >>> os.path.isfile('/tmp/foo.txt/') # False name = name.rstrip(os.sep) if os.path.isfile(name): ret['comment'] = '{0} exists and is not a directory'.format(name) return ret # Add back the slash so that file.makedirs properly creates the # destdir if it needs to be created. file.makedirs expects a trailing # slash in the directory path. name += os.sep if not _path_is_abs(if_missing): ret['comment'] = 'Value for \'if_missing\' is not an absolute path' return ret if not _path_is_abs(enforce_ownership_on): ret['comment'] = ('Value for \'enforce_ownership_on\' is not an ' 'absolute path') return ret else: if enforce_ownership_on is not None: try: not_rel = os.path.relpath(enforce_ownership_on, name).startswith('..' + os.sep) except Exception: # A ValueError is raised on Windows when the paths passed to # os.path.relpath are not on the same drive letter. Using a # generic Exception here to keep other possible exception types # from making this state blow up with a traceback. not_rel = True if not_rel: ret['comment'] = ( 'Value for \'enforce_ownership_on\' must be within {0}' .format(name) ) return ret if if_missing is not None and os.path.exists(if_missing): ret['result'] = True ret['comment'] = 'Path {0} exists'.format(if_missing) return ret if user or group: if salt.utils.platform.is_windows(): ret['comment'] = \ 'User/group ownership cannot be enforced on Windows minions' return ret if user: uid = __salt__['file.user_to_uid'](user) if uid == '': ret['comment'] = 'User {0} does not exist'.format(user) return ret else: uid = -1 if group: gid = __salt__['file.group_to_gid'](group) if gid == '': ret['comment'] = 'Group {0} does not exist'.format(group) return ret else: gid = -1 else: # We should never hit the ownership enforcement code unless user or # group was specified, but just in case, set uid/gid to -1 to make the # os.chown() a no-op and avoid a NameError. uid = gid = -1 if source_hash_update and not source_hash: ret.setdefault('warnings', []).append( 'The \'source_hash_update\' argument is ignored when ' '\'source_hash\' is not also specified.' ) try: source_match = __salt__['file.source_list'](source, source_hash, __env__)[0] except CommandExecutionError as exc: ret['result'] = False ret['comment'] = exc.strerror return ret urlparsed_source = _urlparse(source_match) urlparsed_scheme = urlparsed_source.scheme urlparsed_path = os.path.join( urlparsed_source.netloc, urlparsed_source.path).rstrip(os.sep) # urlparsed_scheme will be the drive letter if this is a Windows file path # This checks for a drive letter as the scheme and changes it to file if urlparsed_scheme and \ urlparsed_scheme.lower() in string.ascii_lowercase: urlparsed_path = ':'.join([urlparsed_scheme, urlparsed_path]) urlparsed_scheme = 'file' source_hash_basename = urlparsed_path or urlparsed_source.netloc source_is_local = urlparsed_scheme in salt.utils.files.LOCAL_PROTOS if source_is_local: # Get rid of "file://" from start of source_match source_match = os.path.realpath(os.path.expanduser(urlparsed_path)) if not os.path.isfile(source_match): ret['comment'] = 'Source file \'{0}\' does not exist'.format( salt.utils.url.redact_http_basic_auth(source_match)) return ret valid_archive_formats = ('tar', 'rar', 'zip') if not archive_format: archive_format = salt.utils.files.guess_archive_type(source_hash_basename) if archive_format is None: ret['comment'] = ( 'Could not guess archive_format from the value of the ' '\'source\' argument. Please set this archive_format to one ' 'of the following: {0}'.format(', '.join(valid_archive_formats)) ) return ret try: archive_format = archive_format.lower() except AttributeError: pass if archive_format not in valid_archive_formats: ret['comment'] = ( 'Invalid archive_format \'{0}\'. Either set it to a supported ' 'value ({1}) or remove this argument and the archive format will ' 'be guesseed based on file extension.'.format( archive_format, ', '.join(valid_archive_formats), ) ) return ret if options is not None and not isinstance(options, six.string_types): options = six.text_type(options) strip_components = None if options and archive_format == 'tar': try: strip_components = int( re.search( r'''--strip(?:-components)?(?:\s+|=)["']?(\d+)["']?''', options ).group(1) ) except (AttributeError, ValueError): pass if archive_format == 'zip': if options: if use_cmd_unzip is None: log.info( 'Presence of CLI options in archive.extracted state for ' '\'%s\' implies that use_cmd_unzip is set to True.', name ) use_cmd_unzip = True elif not use_cmd_unzip: # use_cmd_unzip explicitly disabled ret['comment'] = ( '\'use_cmd_unzip\' cannot be set to False if CLI options ' 'are being specified (via the \'options\' argument). ' 'Either remove \'use_cmd_unzip\', or set it to True.' ) return ret if use_cmd_unzip: if 'archive.cmd_unzip' not in __salt__: ret['comment'] = ( 'archive.cmd_unzip function not available, unzip might ' 'not be installed on minion' ) return ret if password: if use_cmd_unzip is None: log.info( 'Presence of a password in archive.extracted state for ' '\'%s\' implies that use_cmd_unzip is set to False.', name ) use_cmd_unzip = False elif use_cmd_unzip: ret.setdefault('warnings', []).append( 'Using a password in combination with setting ' '\'use_cmd_unzip\' to True is considered insecure. It is ' 'recommended to remove the \'use_cmd_unzip\' argument (or ' 'set it to False) and allow Salt to extract the archive ' 'using Python\'s built-in ZIP file support.' ) else: if password: ret['comment'] = \ 'The \'password\' argument is only supported for zip archives' return ret if archive_format == 'rar': if 'archive.unrar' not in __salt__: ret['comment'] = ( 'archive.unrar function not available, rar/unrar might ' 'not be installed on minion' ) return ret supports_options = ('tar', 'zip') if options and archive_format not in supports_options: ret['comment'] = ( 'The \'options\' argument is only compatible with the following ' 'archive formats: {0}'.format(', '.join(supports_options)) ) return ret if trim_output: if trim_output is True: trim_output = 100 elif not isinstance(trim_output, (bool, six.integer_types)): try: # Try to handle cases where trim_output was passed as a # string-ified integer. trim_output = int(trim_output) except TypeError: ret['comment'] = ( 'Invalid value for trim_output, must be True/False or an ' 'integer' ) return ret if source_hash: try: source_sum = __salt__['file.get_source_sum']( source=source_match, source_hash=source_hash, source_hash_name=source_hash_name, saltenv=__env__) except CommandExecutionError as exc: ret['comment'] = exc.strerror return ret else: source_sum = {} if source_is_local: cached = source_match else: if __opts__['test']: ret['result'] = None ret['comment'] = ( 'Archive {0} would be cached (if necessary) and checked to ' 'discover if extraction is needed'.format( salt.utils.url.redact_http_basic_auth(source_match) ) ) return ret if 'file.cached' not in __states__: # Shouldn't happen unless there is a traceback keeping # salt/states/file.py from being processed through the loader. If # that is the case, we have much more important problems as _all_ # file states would be unavailable. ret['comment'] = ( 'Unable to cache {0}, file.cached state not available'.format( salt.utils.url.redact_http_basic_auth(source_match) ) ) return ret try: result = __states__['file.cached'](source_match, source_hash=source_hash, source_hash_name=source_hash_name, skip_verify=skip_verify, saltenv=__env__) except Exception as exc: msg = 'Failed to cache {0}: {1}'.format( salt.utils.url.redact_http_basic_auth(source_match), exc.__str__()) log.exception(msg) ret['comment'] = msg return ret else: log.debug('file.cached: %s', result) if result['result']: # Get the path of the file in the minion cache cached = __salt__['cp.is_cached'](source_match, saltenv=__env__) else: log.debug( 'failed to download %s', salt.utils.url.redact_http_basic_auth(source_match) ) return result existing_cached_source_sum = _read_cached_checksum(cached) if source_hash and source_hash_update and not skip_verify: # Create local hash sum file if we're going to track sum update _update_checksum(cached) if archive_format == 'zip' and not password: log.debug('Checking %s to see if it is password-protected', source_match) # Either use_cmd_unzip was explicitly set to True, or was # implicitly enabled by setting the "options" argument. try: encrypted_zip = __salt__['archive.is_encrypted']( cached, clean=False, saltenv=__env__) except CommandExecutionError: # This would happen if archive_format=zip and the source archive is # not actually a zip file. pass else: if encrypted_zip: ret['comment'] = ( 'Archive {0} is password-protected, but no password was ' 'specified. Please set the \'password\' argument.'.format( salt.utils.url.redact_http_basic_auth(source_match) ) ) return ret try: contents = __salt__['archive.list'](cached, archive_format=archive_format, options=list_options, strip_components=strip_components, clean=False, verbose=True) except CommandExecutionError as exc: contents = None errors = [] if not if_missing: errors.append('\'if_missing\' must be set') if not enforce_ownership_on and (user or group): errors.append( 'Ownership cannot be managed without setting ' '\'enforce_ownership_on\'.' ) msg = exc.strerror if errors: msg += '\n\n' if archive_format == 'tar': msg += ( 'If the source archive is a tar archive compressed using ' 'a compression type not natively supported by the tar ' 'command, then setting the \'list_options\' argument may ' 'allow the contents to be listed. Otherwise, if Salt is ' 'unable to determine the files/directories in the ' 'archive, the following workaround(s) would need to be ' 'used for this state to proceed' ) else: msg += ( 'The following workarounds must be used for this state to ' 'proceed' ) msg += ( ' (assuming the source file is a valid {0} archive):\n' .format(archive_format) ) for error in errors: msg += '\n- {0}'.format(error) ret['comment'] = msg return ret if enforce_toplevel and contents is not None \ and (len(contents['top_level_dirs']) > 1 or contents['top_level_files']): ret['comment'] = ('Archive does not have a single top-level directory. ' 'To allow this archive to be extracted, set ' '\'enforce_toplevel\' to False. To avoid a ' '\'{0}-bomb\' it may also be advisable to set a ' 'top-level directory by adding it to the \'name\' ' 'value (for example, setting \'name\' to {1} ' 'instead of {2}).'.format( archive_format, os.path.join(name, 'some_dir'), name, )) return ret extraction_needed = overwrite contents_missing = False # Check to see if we need to extract the archive. Using os.lstat() in a # try/except is considerably faster than using os.path.exists(), and we # already need to catch an OSError to cover edge cases where the minion is # running as a non-privileged user and is trying to check for the existence # of a path to which it does not have permission. try: if_missing_path_exists = os.path.exists(if_missing) except TypeError: if_missing_path_exists = False if not if_missing_path_exists: if contents is None: try: os.lstat(if_missing) extraction_needed = False except OSError as exc: if exc.errno == errno.ENOENT: extraction_needed = True else: ret['comment'] = ( 'Failed to check for existence of if_missing path ' '({0}): {1}'.format(if_missing, exc.__str__()) ) return ret else: incorrect_type = [] for path_list, func in \ ((contents['dirs'], stat.S_ISDIR), (contents['files'], lambda x: not stat.S_ISLNK(x) and not stat.S_ISDIR(x)), (contents['links'], stat.S_ISLNK)): for path in path_list: full_path = salt.utils.path.join(name, path) try: path_mode = os.lstat(full_path.rstrip(os.sep)).st_mode if not func(path_mode): incorrect_type.append(path) except OSError as exc: if exc.errno == errno.ENOENT: extraction_needed = True contents_missing = True elif exc.errno != errno.ENOTDIR: # In cases where a directory path was occupied by a # file instead, all os.lstat() calls to files within # that dir will raise an ENOTDIR OSError. So we # expect these and will only abort here if the # error code is something else. ret['comment'] = exc.__str__() return ret if incorrect_type: incorrect_paths = '\n\n' + '\n'.join( ['- {0}'.format(x) for x in incorrect_type] ) ret['comment'] = ( 'The below paths (relative to {0}) exist, but are the ' 'incorrect type (file instead of directory, symlink ' 'instead of file, etc.).'.format(name) ) if __opts__['test'] and clean and contents is not None: ret['result'] = None ret['comment'] += ( ' Since the \'clean\' option is enabled, the ' 'destination paths would be cleared and the ' 'archive would be extracted.{0}'.format( incorrect_paths ) ) return ret # Skip notices of incorrect types if we're cleaning if not (clean and contents is not None): if not force: ret['comment'] += ( ' To proceed with extraction, set \'force\' to ' 'True. Note that this will remove these paths ' 'before extracting.{0}'.format(incorrect_paths) ) return ret else: errors = [] for path in incorrect_type: full_path = os.path.join(name, path) try: salt.utils.files.rm_rf(full_path.rstrip(os.sep)) ret['changes'].setdefault( 'removed', []).append(full_path) extraction_needed = True except OSError as exc: if exc.errno != errno.ENOENT: errors.append(exc.__str__()) if errors: msg = ( 'One or more paths existed by were the incorrect ' 'type (i.e. file instead of directory or ' 'vice-versa), but could not be removed. The ' 'following errors were observed:\n' ) for error in errors: msg += '\n- {0}'.format(error) ret['comment'] = msg return ret if not extraction_needed \ and source_hash_update \ and existing_cached_source_sum is not None \ and not _compare_checksum(cached, existing_cached_source_sum): extraction_needed = True source_hash_trigger = True else: source_hash_trigger = False created_destdir = False if extraction_needed: if source_is_local and source_hash and not skip_verify: ret['result'] = __salt__['file.check_hash'](source_match, source_sum['hsum']) if not ret['result']: ret['comment'] = \ '{0} does not match the desired source_hash {1}'.format( salt.utils.url.redact_http_basic_auth(source_match), source_sum['hsum'] ) return ret if __opts__['test']: ret['result'] = None ret['comment'] = \ 'Archive {0} would be extracted to {1}'.format( salt.utils.url.redact_http_basic_auth(source_match), name ) if clean and contents is not None: ret['comment'] += ', after cleaning destination path(s)' _add_explanation(ret, source_hash_trigger, contents_missing) return ret if clean and contents is not None: errors = [] log.debug('Cleaning archive paths from within %s', name) for path in contents['top_level_dirs'] + contents['top_level_files']: full_path = os.path.join(name, path) try: log.debug('Removing %s', full_path) salt.utils.files.rm_rf(full_path.rstrip(os.sep)) ret['changes'].setdefault( 'removed', []).append(full_path) except OSError as exc: if exc.errno != errno.ENOENT: errors.append(exc.__str__()) if errors: msg = ( 'One or more paths could not be cleaned. The following ' 'errors were observed:\n' ) for error in errors: msg += '\n- {0}'.format(error) ret['comment'] = msg return ret if not os.path.isdir(name): __states__['file.directory'](name, user=user, makedirs=True) created_destdir = True log.debug('Extracting %s to %s', cached, name) try: if archive_format == 'zip': if use_cmd_unzip: try: files = __salt__['archive.cmd_unzip']( cached, name, options=options, trim_output=trim_output, password=password, **kwargs) except (CommandExecutionError, CommandNotFoundError) as exc: ret['comment'] = exc.strerror return ret else: files = __salt__['archive.unzip'](cached, name, options=options, trim_output=trim_output, password=password, extract_perms=extract_perms, **kwargs) elif archive_format == 'rar': try: files = __salt__['archive.unrar'](cached, name, trim_output=trim_output, **kwargs) except (CommandExecutionError, CommandNotFoundError) as exc: ret['comment'] = exc.strerror return ret else: if options is None: try: with closing(tarfile.open(cached, 'r')) as tar: tar.extractall(salt.utils.stringutils.to_str(name)) files = tar.getnames() if trim_output: files = files[:trim_output] except tarfile.ReadError: if salt.utils.path.which('xz'): if __salt__['cmd.retcode']( ['xz', '-t', cached], python_shell=False, ignore_retcode=True) == 0: # XZ-compressed data log.debug( 'Tar file is XZ-compressed, attempting ' 'decompression and extraction using XZ Utils ' 'and the tar command' ) # Must use python_shell=True here because not # all tar implementations support the -J flag # for decompressing XZ-compressed data. We need # to dump the decompressed data to stdout and # pipe it to tar for extraction. cmd = 'xz --decompress --stdout {0} | tar xvf -' results = __salt__['cmd.run_all']( cmd.format(_cmd_quote(cached)), cwd=name, python_shell=True) if results['retcode'] != 0: if created_destdir: _cleanup_destdir(name) ret['result'] = False ret['changes'] = results return ret if _is_bsdtar(): files = results['stderr'] else: files = results['stdout'] else: # Failed to open tar archive and it is not # XZ-compressed, gracefully fail the state if created_destdir: _cleanup_destdir(name) ret['result'] = False ret['comment'] = ( 'Failed to read from tar archive using ' 'Python\'s native tar file support. If ' 'archive is compressed using something ' 'other than gzip or bzip2, the ' '\'options\' argument may be required to ' 'pass the correct options to the tar ' 'command in order to extract the archive.' ) return ret else: if created_destdir: _cleanup_destdir(name) ret['result'] = False ret['comment'] = ( 'Failed to read from tar archive. If it is ' 'XZ-compressed, install xz-utils to attempt ' 'extraction.' ) return ret else: if not salt.utils.path.which('tar'): ret['comment'] = ( 'tar command not available, it might not be ' 'installed on minion' ) return ret tar_opts = shlex.split(options) tar_cmd = ['tar'] tar_shortopts = 'x' tar_longopts = [] for position, opt in enumerate(tar_opts): if opt.startswith('-'): tar_longopts.append(opt) else: if position > 0: tar_longopts.append(opt) else: append_opt = opt append_opt = append_opt.replace('x', '') append_opt = append_opt.replace('f', '') tar_shortopts = tar_shortopts + append_opt if __grains__['os'].lower() == 'openbsd': tar_shortopts = '-' + tar_shortopts tar_cmd.append(tar_shortopts) tar_cmd.extend(tar_longopts) tar_cmd.extend(['-f', cached]) results = __salt__['cmd.run_all'](tar_cmd, cwd=name, python_shell=False) if results['retcode'] != 0: ret['result'] = False ret['changes'] = results return ret if _is_bsdtar(): files = results['stderr'] else: files = results['stdout'] if not files: files = 'no tar output so far' except CommandExecutionError as exc: ret['comment'] = exc.strerror return ret # Recursively set user and group ownership of files enforce_missing = [] enforce_failed = [] if user or group: if enforce_ownership_on: if os.path.isdir(enforce_ownership_on): enforce_dirs = [enforce_ownership_on] enforce_files = [] enforce_links = [] else: enforce_dirs = [] enforce_files = [enforce_ownership_on] enforce_links = [] else: if contents is not None: enforce_dirs = contents['top_level_dirs'] enforce_files = contents['top_level_files'] enforce_links = contents['top_level_links'] recurse = [] if user: recurse.append('user') if group: recurse.append('group') recurse_str = ', '.join(recurse) owner_changes = dict([ (x, y) for x, y in (('user', user), ('group', group)) if y ]) for dirname in enforce_dirs: full_path = os.path.join(name, dirname) if not os.path.isdir(full_path): if not __opts__['test']: enforce_missing.append(full_path) else: log.debug( 'Enforcing %s ownership on %s using a file.directory state%s', recurse_str, dirname, ' (dry-run only)' if __opts__['test'] else '' ) dir_result = __states__['file.directory'](full_path, user=user, group=group, recurse=recurse) log.debug('file.directory: %s', dir_result) if dir_result.get('changes'): ret['changes']['updated ownership'] = True try: if not dir_result['result']: enforce_failed.append(full_path) except (KeyError, TypeError): log.warning( 'Bad state return %s for file.directory state on %s', dir_result, dirname ) for filename in enforce_files + enforce_links: full_path = os.path.join(name, filename) try: # Using os.lstat instead of calling out to # __salt__['file.stats'], since we may be doing this for a lot # of files, and simply calling os.lstat directly will speed # things up a bit. file_stat = os.lstat(full_path) except OSError as exc: if not __opts__['test']: if exc.errno == errno.ENOENT: enforce_missing.append(full_path) enforce_failed.append(full_path) else: # Earlier we set uid, gid to -1 if we're not enforcing # ownership on user, group, as passing -1 to os.chown will tell # it not to change that ownership. Since we've done that, we # can selectively compare the uid/gid from the values in # file_stat, _only if_ the "desired" uid/gid is something other # than -1. if (uid != -1 and uid != file_stat.st_uid) \ or (gid != -1 and gid != file_stat.st_gid): if __opts__['test']: ret['changes']['updated ownership'] = True else: try: os.lchown(full_path, uid, gid) ret['changes']['updated ownership'] = True except OSError: enforce_failed.append(filename) if extraction_needed: if files: if created_destdir: ret['changes']['directories_created'] = [name] ret['changes']['extracted_files'] = files ret['comment'] = '{0} extracted to {1}'.format( salt.utils.url.redact_http_basic_auth(source_match), name, ) _add_explanation(ret, source_hash_trigger, contents_missing) ret['result'] = True else: ret['result'] = False ret['comment'] = 'No files were extracted from {0}'.format( salt.utils.url.redact_http_basic_auth(source_match) ) else: ret['result'] = True if if_missing_path_exists: ret['comment'] = '{0} exists'.format(if_missing) else: ret['comment'] = 'All files in archive are already present' if __opts__['test']: if ret['changes'].get('updated ownership'): ret['result'] = None ret['comment'] += ( '. Ownership would be updated on one or more ' 'files/directories.' ) if enforce_missing: if not if_missing: # If is_missing was used, and both a) the archive had never been # extracted, and b) the path referred to by if_missing exists, then # enforce_missing would contain paths of top_level dirs/files that # _would_ have been extracted. Since if_missing can be used as a # semaphore to conditionally extract, we don't want to make this a # case where the state fails, so we only fail the state if # is_missing is not used. ret['result'] = False ret['comment'] += ( '\n\nWhile trying to enforce user/group ownership, the following ' 'paths were missing:\n' ) for item in enforce_missing: ret['comment'] += '\n- {0}'.format(item) if enforce_failed: ret['result'] = False ret['comment'] += ( '\n\nWhile trying to enforce user/group ownership, Salt was ' 'unable to change ownership on the following paths:\n' ) for item in enforce_failed: ret['comment'] += '\n- {0}'.format(item) if not source_is_local: if keep_source: log.debug('Keeping cached source file %s', cached) else: log.debug('Cleaning cached source file %s', cached) result = __states__['file.not_cached'](source_match, saltenv=__env__) if not result['result']: # Don't let failure to delete cached file cause the state # itself to fail, just drop it in the warnings. ret.setdefault('warnings', []).append(result['comment']) return ret
python
def extracted(name, source, source_hash=None, source_hash_name=None, source_hash_update=False, skip_verify=False, password=None, options=None, list_options=None, force=False, overwrite=False, clean=False, user=None, group=None, if_missing=None, trim_output=False, use_cmd_unzip=None, extract_perms=True, enforce_toplevel=True, enforce_ownership_on=None, archive_format=None, **kwargs): ''' .. versionadded:: 2014.1.0 .. versionchanged:: 2016.11.0 This state has been rewritten. Some arguments are new to this release and will not be available in the 2016.3 release cycle (and earlier). Additionally, the **ZIP Archive Handling** section below applies specifically to the 2016.11.0 release (and newer). Ensure that an archive is extracted to a specific directory. .. important:: **Changes for 2016.11.0** In earlier releases, this state would rely on the ``if_missing`` argument to determine whether or not the archive needed to be extracted. When this argument was not passed, then the state would just assume ``if_missing`` is the same as the ``name`` argument (i.e. the parent directory into which the archive would be extracted). This caused a number of annoyances. One such annoyance was the need to know beforehand a path that would result from the extraction of the archive, and setting ``if_missing`` to that directory, like so: .. code-block:: yaml extract_myapp: archive.extracted: - name: /var/www - source: salt://apps/src/myapp-16.2.4.tar.gz - user: www - group: www - if_missing: /var/www/myapp-16.2.4 If ``/var/www`` already existed, this would effectively make ``if_missing`` a required argument, just to get Salt to extract the archive. Some users worked around this by adding the top-level directory of the archive to the end of the ``name`` argument, and then used ``--strip`` or ``--strip-components`` to remove that top-level dir when extracting: .. code-block:: yaml extract_myapp: archive.extracted: - name: /var/www/myapp-16.2.4 - source: salt://apps/src/myapp-16.2.4.tar.gz - user: www - group: www With the rewrite for 2016.11.0, these workarounds are no longer necessary. ``if_missing`` is still a supported argument, but it is no longer required. The equivalent SLS in 2016.11.0 would be: .. code-block:: yaml extract_myapp: archive.extracted: - name: /var/www - source: salt://apps/src/myapp-16.2.4.tar.gz - user: www - group: www Salt now uses a function called :py:func:`archive.list <salt.modules.archive.list>` to get a list of files/directories in the archive. Using this information, the state can now check the minion to see if any paths are missing, and know whether or not the archive needs to be extracted. This makes the ``if_missing`` argument unnecessary in most use cases. .. important:: **ZIP Archive Handling** *Note: this information applies to 2016.11.0 and later.* Salt has two different functions for extracting ZIP archives: 1. :py:func:`archive.unzip <salt.modules.archive.unzip>`, which uses Python's zipfile_ module to extract ZIP files. 2. :py:func:`archive.cmd_unzip <salt.modules.archive.cmd_unzip>`, which uses the ``unzip`` CLI command to extract ZIP files. Salt will prefer the use of :py:func:`archive.cmd_unzip <salt.modules.archive.cmd_unzip>` when CLI options are specified (via the ``options`` argument), and will otherwise prefer the :py:func:`archive.unzip <salt.modules.archive.unzip>` function. Use of :py:func:`archive.cmd_unzip <salt.modules.archive.cmd_unzip>` can be forced however by setting the ``use_cmd_unzip`` argument to ``True``. By contrast, setting this argument to ``False`` will force usage of :py:func:`archive.unzip <salt.modules.archive.unzip>`. For example: .. code-block:: yaml /var/www: archive.extracted: - source: salt://foo/bar/myapp.zip - use_cmd_unzip: True When ``use_cmd_unzip`` is omitted, Salt will choose which extraction function to use based on the source archive and the arguments passed to the state. When in doubt, simply do not set this argument; it is provided as a means of overriding the logic Salt uses to decide which function to use. There are differences in the features available in both extraction functions. These are detailed below. - *Command-line options* (only supported by :py:func:`archive.cmd_unzip <salt.modules.archive.cmd_unzip>`) - When the ``options`` argument is used, :py:func:`archive.cmd_unzip <salt.modules.archive.cmd_unzip>` is the only function that can be used to extract the archive. Therefore, if ``use_cmd_unzip`` is specified and set to ``False``, and ``options`` is also set, the state will not proceed. - *Permissions* - Due to an `upstream bug in Python`_, permissions are not preserved when the zipfile_ module is used to extract an archive. As of the 2016.11.0 release, :py:func:`archive.unzip <salt.modules.archive.unzip>` (as well as this state) has an ``extract_perms`` argument which, when set to ``True`` (the default), will attempt to match the permissions of the extracted files/directories to those defined within the archive. To disable this functionality and have the state not attempt to preserve the permissions from the ZIP archive, set ``extract_perms`` to ``False``: .. code-block:: yaml /var/www: archive.extracted: - source: salt://foo/bar/myapp.zip - extract_perms: False .. _`upstream bug in Python`: https://bugs.python.org/issue15795 name Directory into which the archive should be extracted source Archive to be extracted .. note:: This argument uses the same syntax as its counterpart in the :py:func:`file.managed <salt.states.file.managed>` state. source_hash Hash of source file, or file with list of hash-to-file mappings .. note:: This argument uses the same syntax as its counterpart in the :py:func:`file.managed <salt.states.file.managed>` state. .. versionchanged:: 2016.11.0 If this argument specifies the hash itself, instead of a URI to a file containing hashes, the hash type can now be omitted and Salt will determine the hash type based on the length of the hash. For example, both of the below states are now valid, while before only the second one would be: .. code-block:: yaml foo_app: archive.extracted: - name: /var/www - source: https://mydomain.tld/foo.tar.gz - source_hash: 3360db35e682f1c5f9c58aa307de16d41361618c bar_app: archive.extracted: - name: /var/www - source: https://mydomain.tld/bar.tar.gz - source_hash: sha1=5edb7d584b82ddcbf76e311601f5d4442974aaa5 source_hash_name When ``source_hash`` refers to a hash file, Salt will try to find the correct hash by matching the filename part of the ``source`` URI. When managing a file with a ``source`` of ``salt://files/foo.tar.gz``, then the following line in a hash file would match: .. code-block:: text acbd18db4cc2f85cedef654fccc4a4d8 foo.tar.gz This line would also match: .. code-block:: text acbd18db4cc2f85cedef654fccc4a4d8 ./dir1/foo.tar.gz However, sometimes a hash file will include multiple similar paths: .. code-block:: text 37b51d194a7513e45b56f6524f2d51f2 ./dir1/foo.txt acbd18db4cc2f85cedef654fccc4a4d8 ./dir2/foo.txt 73feffa4b7f6bb68e44cf984c85f6e88 ./dir3/foo.txt In cases like this, Salt may match the incorrect hash. This argument can be used to tell Salt which filename to match, to ensure that the correct hash is identified. For example: .. code-block:: yaml /var/www: archive.extracted: - source: https://mydomain.tld/dir2/foo.tar.gz - source_hash: https://mydomain.tld/hashes - source_hash_name: ./dir2/foo.tar.gz .. note:: This argument must contain the full filename entry from the checksum file, as this argument is meant to disambiguate matches for multiple files that have the same basename. So, in the example above, simply using ``foo.txt`` would not match. .. versionadded:: 2016.11.0 source_hash_update : False Set this to ``True`` if archive should be extracted if source_hash has changed. This would extract regardless of the ``if_missing`` parameter. Note that this is only checked if the ``source`` value has not changed. If it has (e.g. to increment a version number in the path) then the archive will not be extracted even if the hash has changed. .. versionadded:: 2016.3.0 skip_verify : False If ``True``, hash verification of remote file sources (``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored. .. versionadded:: 2016.3.4 keep_source : True For ``source`` archives not local to the minion (i.e. from the Salt fileserver or a remote source such as ``http(s)`` or ``ftp``), Salt will need to download the archive to the minion cache before they can be extracted. To remove the downloaded archive after extraction, set this argument to ``False``. .. versionadded:: 2017.7.3 keep : True Same as ``keep_source``, kept for backward-compatibility. .. note:: If both ``keep_source`` and ``keep`` are used, ``keep`` will be ignored. password **For ZIP archives only.** Password used for extraction. .. versionadded:: 2016.3.0 .. versionchanged:: 2016.11.0 The newly-added :py:func:`archive.is_encrypted <salt.modules.archive.is_encrypted>` function will be used to determine if the archive is password-protected. If it is, then the ``password`` argument will be required for the state to proceed. options **For tar and zip archives only.** This option can be used to specify a string of additional arguments to pass to the tar/zip command. If this argument is not used, then the minion will attempt to use Python's native tarfile_/zipfile_ support to extract it. For zip archives, this argument is mostly used to overwrite existing files with ``o``. Using this argument means that the ``tar`` or ``unzip`` command will be used, which is less platform-independent, so keep this in mind when using this option; the CLI options must be valid options for the ``tar``/``unzip`` implementation on the minion's OS. .. versionadded:: 2016.11.0 .. versionchanged:: 2015.8.11,2016.3.2 XZ-compressed tar archives no longer require ``J`` to manually be set in the ``options``, they are now detected automatically and decompressed using the xz_ CLI command and extracted using ``tar xvf``. This is a more platform-independent solution, as not all tar implementations support the ``J`` argument for extracting archives. .. note:: For tar archives, main operators like ``-x``, ``--extract``, ``--get``, ``-c`` and ``-f``/``--file`` should *not* be used here. list_options **For tar archives only.** This state uses :py:func:`archive.list <salt.modules.archive.list_>` to discover the contents of the source archive so that it knows which file paths should exist on the minion if the archive has already been extracted. For the vast majority of tar archives, :py:func:`archive.list <salt.modules.archive.list_>` "just works". Archives compressed using gzip, bzip2, and xz/lzma (with the help of the xz_ CLI command) are supported automatically. However, for archives compressed using other compression types, CLI options must be passed to :py:func:`archive.list <salt.modules.archive.list_>`. This argument will be passed through to :py:func:`archive.list <salt.modules.archive.list_>` as its ``options`` argument, to allow it to successfully list the archive's contents. For the vast majority of archives, this argument should not need to be used, it should only be needed in cases where the state fails with an error stating that the archive's contents could not be listed. .. versionadded:: 2016.11.0 force : False If a path that should be occupied by a file in the extracted result is instead a directory (or vice-versa), the state will fail. Set this argument to ``True`` to force these paths to be removed in order to allow the archive to be extracted. .. warning:: Use this option *very* carefully. .. versionadded:: 2016.11.0 overwrite : False Set this to ``True`` to force the archive to be extracted. This is useful for cases where the filenames/directories have not changed, but the content of the files have. .. versionadded:: 2016.11.1 clean : False Set this to ``True`` to remove any top-level files and recursively remove any top-level directory paths before extracting. .. note:: Files will only be cleaned first if extracting the archive is deemed necessary, either by paths missing on the minion, or if ``overwrite`` is set to ``True``. .. versionadded:: 2016.11.1 user The user to own each extracted file. Not available on Windows. .. versionadded:: 2015.8.0 .. versionchanged:: 2016.3.0 When used in combination with ``if_missing``, ownership will only be enforced if ``if_missing`` is a directory. .. versionchanged:: 2016.11.0 Ownership will be enforced only on the file/directory paths found by running :py:func:`archive.list <salt.modules.archive.list_>` on the source archive. An alternative root directory on which to enforce ownership can be specified using the ``enforce_ownership_on`` argument. group The group to own each extracted file. Not available on Windows. .. versionadded:: 2015.8.0 .. versionchanged:: 2016.3.0 When used in combination with ``if_missing``, ownership will only be enforced if ``if_missing`` is a directory. .. versionchanged:: 2016.11.0 Ownership will be enforced only on the file/directory paths found by running :py:func:`archive.list <salt.modules.archive.list_>` on the source archive. An alternative root directory on which to enforce ownership can be specified using the ``enforce_ownership_on`` argument. if_missing If specified, this path will be checked, and if it exists then the archive will not be extracted. This path can be either a directory or a file, so this option can also be used to check for a semaphore file and conditionally skip extraction. .. versionchanged:: 2016.3.0 When used in combination with either ``user`` or ``group``, ownership will only be enforced when ``if_missing`` is a directory. .. versionchanged:: 2016.11.0 Ownership enforcement is no longer tied to this argument, it is simply checked for existence and extraction will be skipped if if is present. trim_output : False Useful for archives with many files in them. This can either be set to ``True`` (in which case only the first 100 files extracted will be in the state results), or it can be set to an integer for more exact control over the max number of files to include in the state results. .. versionadded:: 2016.3.0 use_cmd_unzip : False Set to ``True`` for zip files to force usage of the :py:func:`archive.cmd_unzip <salt.modules.archive.cmd_unzip>` function to extract. .. versionadded:: 2016.11.0 extract_perms : True **For ZIP archives only.** When using :py:func:`archive.unzip <salt.modules.archive.unzip>` to extract ZIP archives, Salt works around an `upstream bug in Python`_ to set the permissions on extracted files/directories to match those encoded into the ZIP archive. Set this argument to ``False`` to skip this workaround. .. versionadded:: 2016.11.0 enforce_toplevel : True This option will enforce a single directory at the top level of the source archive, to prevent extracting a 'tar-bomb'. Set this argument to ``False`` to allow archives with files (or multiple directories) at the top level to be extracted. .. versionadded:: 2016.11.0 enforce_ownership_on When ``user`` or ``group`` is specified, Salt will default to enforcing permissions on the file/directory paths detected by running :py:func:`archive.list <salt.modules.archive.list_>` on the source archive. Use this argument to specify an alternate directory on which ownership should be enforced. .. note:: This path must be within the path specified by the ``name`` argument. .. versionadded:: 2016.11.0 archive_format One of ``tar``, ``zip``, or ``rar``. .. versionchanged:: 2016.11.0 If omitted, the archive format will be guessed based on the value of the ``source`` argument. If the minion is running a release older than 2016.11.0, this option is required. .. _tarfile: https://docs.python.org/2/library/tarfile.html .. _zipfile: https://docs.python.org/2/library/zipfile.html .. _xz: http://tukaani.org/xz/ **Examples** 1. tar with lmza (i.e. xz) compression: .. code-block:: yaml graylog2-server: archive.extracted: - name: /opt/ - source: https://github.com/downloads/Graylog2/graylog2-server/graylog2-server-0.9.6p1.tar.lzma - source_hash: md5=499ae16dcae71eeb7c3a30c75ea7a1a6 2. tar archive with flag for verbose output, and enforcement of user/group ownership: .. code-block:: yaml graylog2-server: archive.extracted: - name: /opt/ - source: https://github.com/downloads/Graylog2/graylog2-server/graylog2-server-0.9.6p1.tar.gz - source_hash: md5=499ae16dcae71eeb7c3a30c75ea7a1a6 - options: v - user: foo - group: foo 3. tar archive, with ``source_hash_update`` set to ``True`` to prevent state from attempting extraction unless the ``source_hash`` differs from the previous time the archive was extracted: .. code-block:: yaml graylog2-server: archive.extracted: - name: /opt/ - source: https://github.com/downloads/Graylog2/graylog2-server/graylog2-server-0.9.6p1.tar.lzma - source_hash: md5=499ae16dcae71eeb7c3a30c75ea7a1a6 - source_hash_update: True ''' ret = {'name': name, 'result': False, 'changes': {}, 'comment': ''} # Remove pub kwargs as they're irrelevant here. kwargs = salt.utils.args.clean_kwargs(**kwargs) if 'keep_source' in kwargs and 'keep' in kwargs: ret.setdefault('warnings', []).append( 'Both \'keep_source\' and \'keep\' were used. Since these both ' 'do the same thing, \'keep\' was ignored.' ) keep_source = bool(kwargs.pop('keep_source')) kwargs.pop('keep') elif 'keep_source' in kwargs: keep_source = bool(kwargs.pop('keep_source')) elif 'keep' in kwargs: keep_source = bool(kwargs.pop('keep')) else: # Neither was passed, default is True keep_source = True if not _path_is_abs(name): ret['comment'] = '{0} is not an absolute path'.format(name) return ret else: if not name: # Empty name, like None, '' etc. ret['comment'] = 'Name of the directory path needs to be specified' return ret # os.path.isfile() returns False when there is a trailing slash, hence # our need for first stripping the slash and then adding it back later. # Otherwise, we can't properly check if the extraction location both a) # exists and b) is a file. # # >>> os.path.isfile('/tmp/foo.txt') # True # >>> os.path.isfile('/tmp/foo.txt/') # False name = name.rstrip(os.sep) if os.path.isfile(name): ret['comment'] = '{0} exists and is not a directory'.format(name) return ret # Add back the slash so that file.makedirs properly creates the # destdir if it needs to be created. file.makedirs expects a trailing # slash in the directory path. name += os.sep if not _path_is_abs(if_missing): ret['comment'] = 'Value for \'if_missing\' is not an absolute path' return ret if not _path_is_abs(enforce_ownership_on): ret['comment'] = ('Value for \'enforce_ownership_on\' is not an ' 'absolute path') return ret else: if enforce_ownership_on is not None: try: not_rel = os.path.relpath(enforce_ownership_on, name).startswith('..' + os.sep) except Exception: # A ValueError is raised on Windows when the paths passed to # os.path.relpath are not on the same drive letter. Using a # generic Exception here to keep other possible exception types # from making this state blow up with a traceback. not_rel = True if not_rel: ret['comment'] = ( 'Value for \'enforce_ownership_on\' must be within {0}' .format(name) ) return ret if if_missing is not None and os.path.exists(if_missing): ret['result'] = True ret['comment'] = 'Path {0} exists'.format(if_missing) return ret if user or group: if salt.utils.platform.is_windows(): ret['comment'] = \ 'User/group ownership cannot be enforced on Windows minions' return ret if user: uid = __salt__['file.user_to_uid'](user) if uid == '': ret['comment'] = 'User {0} does not exist'.format(user) return ret else: uid = -1 if group: gid = __salt__['file.group_to_gid'](group) if gid == '': ret['comment'] = 'Group {0} does not exist'.format(group) return ret else: gid = -1 else: # We should never hit the ownership enforcement code unless user or # group was specified, but just in case, set uid/gid to -1 to make the # os.chown() a no-op and avoid a NameError. uid = gid = -1 if source_hash_update and not source_hash: ret.setdefault('warnings', []).append( 'The \'source_hash_update\' argument is ignored when ' '\'source_hash\' is not also specified.' ) try: source_match = __salt__['file.source_list'](source, source_hash, __env__)[0] except CommandExecutionError as exc: ret['result'] = False ret['comment'] = exc.strerror return ret urlparsed_source = _urlparse(source_match) urlparsed_scheme = urlparsed_source.scheme urlparsed_path = os.path.join( urlparsed_source.netloc, urlparsed_source.path).rstrip(os.sep) # urlparsed_scheme will be the drive letter if this is a Windows file path # This checks for a drive letter as the scheme and changes it to file if urlparsed_scheme and \ urlparsed_scheme.lower() in string.ascii_lowercase: urlparsed_path = ':'.join([urlparsed_scheme, urlparsed_path]) urlparsed_scheme = 'file' source_hash_basename = urlparsed_path or urlparsed_source.netloc source_is_local = urlparsed_scheme in salt.utils.files.LOCAL_PROTOS if source_is_local: # Get rid of "file://" from start of source_match source_match = os.path.realpath(os.path.expanduser(urlparsed_path)) if not os.path.isfile(source_match): ret['comment'] = 'Source file \'{0}\' does not exist'.format( salt.utils.url.redact_http_basic_auth(source_match)) return ret valid_archive_formats = ('tar', 'rar', 'zip') if not archive_format: archive_format = salt.utils.files.guess_archive_type(source_hash_basename) if archive_format is None: ret['comment'] = ( 'Could not guess archive_format from the value of the ' '\'source\' argument. Please set this archive_format to one ' 'of the following: {0}'.format(', '.join(valid_archive_formats)) ) return ret try: archive_format = archive_format.lower() except AttributeError: pass if archive_format not in valid_archive_formats: ret['comment'] = ( 'Invalid archive_format \'{0}\'. Either set it to a supported ' 'value ({1}) or remove this argument and the archive format will ' 'be guesseed based on file extension.'.format( archive_format, ', '.join(valid_archive_formats), ) ) return ret if options is not None and not isinstance(options, six.string_types): options = six.text_type(options) strip_components = None if options and archive_format == 'tar': try: strip_components = int( re.search( r'''--strip(?:-components)?(?:\s+|=)["']?(\d+)["']?''', options ).group(1) ) except (AttributeError, ValueError): pass if archive_format == 'zip': if options: if use_cmd_unzip is None: log.info( 'Presence of CLI options in archive.extracted state for ' '\'%s\' implies that use_cmd_unzip is set to True.', name ) use_cmd_unzip = True elif not use_cmd_unzip: # use_cmd_unzip explicitly disabled ret['comment'] = ( '\'use_cmd_unzip\' cannot be set to False if CLI options ' 'are being specified (via the \'options\' argument). ' 'Either remove \'use_cmd_unzip\', or set it to True.' ) return ret if use_cmd_unzip: if 'archive.cmd_unzip' not in __salt__: ret['comment'] = ( 'archive.cmd_unzip function not available, unzip might ' 'not be installed on minion' ) return ret if password: if use_cmd_unzip is None: log.info( 'Presence of a password in archive.extracted state for ' '\'%s\' implies that use_cmd_unzip is set to False.', name ) use_cmd_unzip = False elif use_cmd_unzip: ret.setdefault('warnings', []).append( 'Using a password in combination with setting ' '\'use_cmd_unzip\' to True is considered insecure. It is ' 'recommended to remove the \'use_cmd_unzip\' argument (or ' 'set it to False) and allow Salt to extract the archive ' 'using Python\'s built-in ZIP file support.' ) else: if password: ret['comment'] = \ 'The \'password\' argument is only supported for zip archives' return ret if archive_format == 'rar': if 'archive.unrar' not in __salt__: ret['comment'] = ( 'archive.unrar function not available, rar/unrar might ' 'not be installed on minion' ) return ret supports_options = ('tar', 'zip') if options and archive_format not in supports_options: ret['comment'] = ( 'The \'options\' argument is only compatible with the following ' 'archive formats: {0}'.format(', '.join(supports_options)) ) return ret if trim_output: if trim_output is True: trim_output = 100 elif not isinstance(trim_output, (bool, six.integer_types)): try: # Try to handle cases where trim_output was passed as a # string-ified integer. trim_output = int(trim_output) except TypeError: ret['comment'] = ( 'Invalid value for trim_output, must be True/False or an ' 'integer' ) return ret if source_hash: try: source_sum = __salt__['file.get_source_sum']( source=source_match, source_hash=source_hash, source_hash_name=source_hash_name, saltenv=__env__) except CommandExecutionError as exc: ret['comment'] = exc.strerror return ret else: source_sum = {} if source_is_local: cached = source_match else: if __opts__['test']: ret['result'] = None ret['comment'] = ( 'Archive {0} would be cached (if necessary) and checked to ' 'discover if extraction is needed'.format( salt.utils.url.redact_http_basic_auth(source_match) ) ) return ret if 'file.cached' not in __states__: # Shouldn't happen unless there is a traceback keeping # salt/states/file.py from being processed through the loader. If # that is the case, we have much more important problems as _all_ # file states would be unavailable. ret['comment'] = ( 'Unable to cache {0}, file.cached state not available'.format( salt.utils.url.redact_http_basic_auth(source_match) ) ) return ret try: result = __states__['file.cached'](source_match, source_hash=source_hash, source_hash_name=source_hash_name, skip_verify=skip_verify, saltenv=__env__) except Exception as exc: msg = 'Failed to cache {0}: {1}'.format( salt.utils.url.redact_http_basic_auth(source_match), exc.__str__()) log.exception(msg) ret['comment'] = msg return ret else: log.debug('file.cached: %s', result) if result['result']: # Get the path of the file in the minion cache cached = __salt__['cp.is_cached'](source_match, saltenv=__env__) else: log.debug( 'failed to download %s', salt.utils.url.redact_http_basic_auth(source_match) ) return result existing_cached_source_sum = _read_cached_checksum(cached) if source_hash and source_hash_update and not skip_verify: # Create local hash sum file if we're going to track sum update _update_checksum(cached) if archive_format == 'zip' and not password: log.debug('Checking %s to see if it is password-protected', source_match) # Either use_cmd_unzip was explicitly set to True, or was # implicitly enabled by setting the "options" argument. try: encrypted_zip = __salt__['archive.is_encrypted']( cached, clean=False, saltenv=__env__) except CommandExecutionError: # This would happen if archive_format=zip and the source archive is # not actually a zip file. pass else: if encrypted_zip: ret['comment'] = ( 'Archive {0} is password-protected, but no password was ' 'specified. Please set the \'password\' argument.'.format( salt.utils.url.redact_http_basic_auth(source_match) ) ) return ret try: contents = __salt__['archive.list'](cached, archive_format=archive_format, options=list_options, strip_components=strip_components, clean=False, verbose=True) except CommandExecutionError as exc: contents = None errors = [] if not if_missing: errors.append('\'if_missing\' must be set') if not enforce_ownership_on and (user or group): errors.append( 'Ownership cannot be managed without setting ' '\'enforce_ownership_on\'.' ) msg = exc.strerror if errors: msg += '\n\n' if archive_format == 'tar': msg += ( 'If the source archive is a tar archive compressed using ' 'a compression type not natively supported by the tar ' 'command, then setting the \'list_options\' argument may ' 'allow the contents to be listed. Otherwise, if Salt is ' 'unable to determine the files/directories in the ' 'archive, the following workaround(s) would need to be ' 'used for this state to proceed' ) else: msg += ( 'The following workarounds must be used for this state to ' 'proceed' ) msg += ( ' (assuming the source file is a valid {0} archive):\n' .format(archive_format) ) for error in errors: msg += '\n- {0}'.format(error) ret['comment'] = msg return ret if enforce_toplevel and contents is not None \ and (len(contents['top_level_dirs']) > 1 or contents['top_level_files']): ret['comment'] = ('Archive does not have a single top-level directory. ' 'To allow this archive to be extracted, set ' '\'enforce_toplevel\' to False. To avoid a ' '\'{0}-bomb\' it may also be advisable to set a ' 'top-level directory by adding it to the \'name\' ' 'value (for example, setting \'name\' to {1} ' 'instead of {2}).'.format( archive_format, os.path.join(name, 'some_dir'), name, )) return ret extraction_needed = overwrite contents_missing = False # Check to see if we need to extract the archive. Using os.lstat() in a # try/except is considerably faster than using os.path.exists(), and we # already need to catch an OSError to cover edge cases where the minion is # running as a non-privileged user and is trying to check for the existence # of a path to which it does not have permission. try: if_missing_path_exists = os.path.exists(if_missing) except TypeError: if_missing_path_exists = False if not if_missing_path_exists: if contents is None: try: os.lstat(if_missing) extraction_needed = False except OSError as exc: if exc.errno == errno.ENOENT: extraction_needed = True else: ret['comment'] = ( 'Failed to check for existence of if_missing path ' '({0}): {1}'.format(if_missing, exc.__str__()) ) return ret else: incorrect_type = [] for path_list, func in \ ((contents['dirs'], stat.S_ISDIR), (contents['files'], lambda x: not stat.S_ISLNK(x) and not stat.S_ISDIR(x)), (contents['links'], stat.S_ISLNK)): for path in path_list: full_path = salt.utils.path.join(name, path) try: path_mode = os.lstat(full_path.rstrip(os.sep)).st_mode if not func(path_mode): incorrect_type.append(path) except OSError as exc: if exc.errno == errno.ENOENT: extraction_needed = True contents_missing = True elif exc.errno != errno.ENOTDIR: # In cases where a directory path was occupied by a # file instead, all os.lstat() calls to files within # that dir will raise an ENOTDIR OSError. So we # expect these and will only abort here if the # error code is something else. ret['comment'] = exc.__str__() return ret if incorrect_type: incorrect_paths = '\n\n' + '\n'.join( ['- {0}'.format(x) for x in incorrect_type] ) ret['comment'] = ( 'The below paths (relative to {0}) exist, but are the ' 'incorrect type (file instead of directory, symlink ' 'instead of file, etc.).'.format(name) ) if __opts__['test'] and clean and contents is not None: ret['result'] = None ret['comment'] += ( ' Since the \'clean\' option is enabled, the ' 'destination paths would be cleared and the ' 'archive would be extracted.{0}'.format( incorrect_paths ) ) return ret # Skip notices of incorrect types if we're cleaning if not (clean and contents is not None): if not force: ret['comment'] += ( ' To proceed with extraction, set \'force\' to ' 'True. Note that this will remove these paths ' 'before extracting.{0}'.format(incorrect_paths) ) return ret else: errors = [] for path in incorrect_type: full_path = os.path.join(name, path) try: salt.utils.files.rm_rf(full_path.rstrip(os.sep)) ret['changes'].setdefault( 'removed', []).append(full_path) extraction_needed = True except OSError as exc: if exc.errno != errno.ENOENT: errors.append(exc.__str__()) if errors: msg = ( 'One or more paths existed by were the incorrect ' 'type (i.e. file instead of directory or ' 'vice-versa), but could not be removed. The ' 'following errors were observed:\n' ) for error in errors: msg += '\n- {0}'.format(error) ret['comment'] = msg return ret if not extraction_needed \ and source_hash_update \ and existing_cached_source_sum is not None \ and not _compare_checksum(cached, existing_cached_source_sum): extraction_needed = True source_hash_trigger = True else: source_hash_trigger = False created_destdir = False if extraction_needed: if source_is_local and source_hash and not skip_verify: ret['result'] = __salt__['file.check_hash'](source_match, source_sum['hsum']) if not ret['result']: ret['comment'] = \ '{0} does not match the desired source_hash {1}'.format( salt.utils.url.redact_http_basic_auth(source_match), source_sum['hsum'] ) return ret if __opts__['test']: ret['result'] = None ret['comment'] = \ 'Archive {0} would be extracted to {1}'.format( salt.utils.url.redact_http_basic_auth(source_match), name ) if clean and contents is not None: ret['comment'] += ', after cleaning destination path(s)' _add_explanation(ret, source_hash_trigger, contents_missing) return ret if clean and contents is not None: errors = [] log.debug('Cleaning archive paths from within %s', name) for path in contents['top_level_dirs'] + contents['top_level_files']: full_path = os.path.join(name, path) try: log.debug('Removing %s', full_path) salt.utils.files.rm_rf(full_path.rstrip(os.sep)) ret['changes'].setdefault( 'removed', []).append(full_path) except OSError as exc: if exc.errno != errno.ENOENT: errors.append(exc.__str__()) if errors: msg = ( 'One or more paths could not be cleaned. The following ' 'errors were observed:\n' ) for error in errors: msg += '\n- {0}'.format(error) ret['comment'] = msg return ret if not os.path.isdir(name): __states__['file.directory'](name, user=user, makedirs=True) created_destdir = True log.debug('Extracting %s to %s', cached, name) try: if archive_format == 'zip': if use_cmd_unzip: try: files = __salt__['archive.cmd_unzip']( cached, name, options=options, trim_output=trim_output, password=password, **kwargs) except (CommandExecutionError, CommandNotFoundError) as exc: ret['comment'] = exc.strerror return ret else: files = __salt__['archive.unzip'](cached, name, options=options, trim_output=trim_output, password=password, extract_perms=extract_perms, **kwargs) elif archive_format == 'rar': try: files = __salt__['archive.unrar'](cached, name, trim_output=trim_output, **kwargs) except (CommandExecutionError, CommandNotFoundError) as exc: ret['comment'] = exc.strerror return ret else: if options is None: try: with closing(tarfile.open(cached, 'r')) as tar: tar.extractall(salt.utils.stringutils.to_str(name)) files = tar.getnames() if trim_output: files = files[:trim_output] except tarfile.ReadError: if salt.utils.path.which('xz'): if __salt__['cmd.retcode']( ['xz', '-t', cached], python_shell=False, ignore_retcode=True) == 0: # XZ-compressed data log.debug( 'Tar file is XZ-compressed, attempting ' 'decompression and extraction using XZ Utils ' 'and the tar command' ) # Must use python_shell=True here because not # all tar implementations support the -J flag # for decompressing XZ-compressed data. We need # to dump the decompressed data to stdout and # pipe it to tar for extraction. cmd = 'xz --decompress --stdout {0} | tar xvf -' results = __salt__['cmd.run_all']( cmd.format(_cmd_quote(cached)), cwd=name, python_shell=True) if results['retcode'] != 0: if created_destdir: _cleanup_destdir(name) ret['result'] = False ret['changes'] = results return ret if _is_bsdtar(): files = results['stderr'] else: files = results['stdout'] else: # Failed to open tar archive and it is not # XZ-compressed, gracefully fail the state if created_destdir: _cleanup_destdir(name) ret['result'] = False ret['comment'] = ( 'Failed to read from tar archive using ' 'Python\'s native tar file support. If ' 'archive is compressed using something ' 'other than gzip or bzip2, the ' '\'options\' argument may be required to ' 'pass the correct options to the tar ' 'command in order to extract the archive.' ) return ret else: if created_destdir: _cleanup_destdir(name) ret['result'] = False ret['comment'] = ( 'Failed to read from tar archive. If it is ' 'XZ-compressed, install xz-utils to attempt ' 'extraction.' ) return ret else: if not salt.utils.path.which('tar'): ret['comment'] = ( 'tar command not available, it might not be ' 'installed on minion' ) return ret tar_opts = shlex.split(options) tar_cmd = ['tar'] tar_shortopts = 'x' tar_longopts = [] for position, opt in enumerate(tar_opts): if opt.startswith('-'): tar_longopts.append(opt) else: if position > 0: tar_longopts.append(opt) else: append_opt = opt append_opt = append_opt.replace('x', '') append_opt = append_opt.replace('f', '') tar_shortopts = tar_shortopts + append_opt if __grains__['os'].lower() == 'openbsd': tar_shortopts = '-' + tar_shortopts tar_cmd.append(tar_shortopts) tar_cmd.extend(tar_longopts) tar_cmd.extend(['-f', cached]) results = __salt__['cmd.run_all'](tar_cmd, cwd=name, python_shell=False) if results['retcode'] != 0: ret['result'] = False ret['changes'] = results return ret if _is_bsdtar(): files = results['stderr'] else: files = results['stdout'] if not files: files = 'no tar output so far' except CommandExecutionError as exc: ret['comment'] = exc.strerror return ret # Recursively set user and group ownership of files enforce_missing = [] enforce_failed = [] if user or group: if enforce_ownership_on: if os.path.isdir(enforce_ownership_on): enforce_dirs = [enforce_ownership_on] enforce_files = [] enforce_links = [] else: enforce_dirs = [] enforce_files = [enforce_ownership_on] enforce_links = [] else: if contents is not None: enforce_dirs = contents['top_level_dirs'] enforce_files = contents['top_level_files'] enforce_links = contents['top_level_links'] recurse = [] if user: recurse.append('user') if group: recurse.append('group') recurse_str = ', '.join(recurse) owner_changes = dict([ (x, y) for x, y in (('user', user), ('group', group)) if y ]) for dirname in enforce_dirs: full_path = os.path.join(name, dirname) if not os.path.isdir(full_path): if not __opts__['test']: enforce_missing.append(full_path) else: log.debug( 'Enforcing %s ownership on %s using a file.directory state%s', recurse_str, dirname, ' (dry-run only)' if __opts__['test'] else '' ) dir_result = __states__['file.directory'](full_path, user=user, group=group, recurse=recurse) log.debug('file.directory: %s', dir_result) if dir_result.get('changes'): ret['changes']['updated ownership'] = True try: if not dir_result['result']: enforce_failed.append(full_path) except (KeyError, TypeError): log.warning( 'Bad state return %s for file.directory state on %s', dir_result, dirname ) for filename in enforce_files + enforce_links: full_path = os.path.join(name, filename) try: # Using os.lstat instead of calling out to # __salt__['file.stats'], since we may be doing this for a lot # of files, and simply calling os.lstat directly will speed # things up a bit. file_stat = os.lstat(full_path) except OSError as exc: if not __opts__['test']: if exc.errno == errno.ENOENT: enforce_missing.append(full_path) enforce_failed.append(full_path) else: # Earlier we set uid, gid to -1 if we're not enforcing # ownership on user, group, as passing -1 to os.chown will tell # it not to change that ownership. Since we've done that, we # can selectively compare the uid/gid from the values in # file_stat, _only if_ the "desired" uid/gid is something other # than -1. if (uid != -1 and uid != file_stat.st_uid) \ or (gid != -1 and gid != file_stat.st_gid): if __opts__['test']: ret['changes']['updated ownership'] = True else: try: os.lchown(full_path, uid, gid) ret['changes']['updated ownership'] = True except OSError: enforce_failed.append(filename) if extraction_needed: if files: if created_destdir: ret['changes']['directories_created'] = [name] ret['changes']['extracted_files'] = files ret['comment'] = '{0} extracted to {1}'.format( salt.utils.url.redact_http_basic_auth(source_match), name, ) _add_explanation(ret, source_hash_trigger, contents_missing) ret['result'] = True else: ret['result'] = False ret['comment'] = 'No files were extracted from {0}'.format( salt.utils.url.redact_http_basic_auth(source_match) ) else: ret['result'] = True if if_missing_path_exists: ret['comment'] = '{0} exists'.format(if_missing) else: ret['comment'] = 'All files in archive are already present' if __opts__['test']: if ret['changes'].get('updated ownership'): ret['result'] = None ret['comment'] += ( '. Ownership would be updated on one or more ' 'files/directories.' ) if enforce_missing: if not if_missing: # If is_missing was used, and both a) the archive had never been # extracted, and b) the path referred to by if_missing exists, then # enforce_missing would contain paths of top_level dirs/files that # _would_ have been extracted. Since if_missing can be used as a # semaphore to conditionally extract, we don't want to make this a # case where the state fails, so we only fail the state if # is_missing is not used. ret['result'] = False ret['comment'] += ( '\n\nWhile trying to enforce user/group ownership, the following ' 'paths were missing:\n' ) for item in enforce_missing: ret['comment'] += '\n- {0}'.format(item) if enforce_failed: ret['result'] = False ret['comment'] += ( '\n\nWhile trying to enforce user/group ownership, Salt was ' 'unable to change ownership on the following paths:\n' ) for item in enforce_failed: ret['comment'] += '\n- {0}'.format(item) if not source_is_local: if keep_source: log.debug('Keeping cached source file %s', cached) else: log.debug('Cleaning cached source file %s', cached) result = __states__['file.not_cached'](source_match, saltenv=__env__) if not result['result']: # Don't let failure to delete cached file cause the state # itself to fail, just drop it in the warnings. ret.setdefault('warnings', []).append(result['comment']) return ret
[ "def", "extracted", "(", "name", ",", "source", ",", "source_hash", "=", "None", ",", "source_hash_name", "=", "None", ",", "source_hash_update", "=", "False", ",", "skip_verify", "=", "False", ",", "password", "=", "None", ",", "options", "=", "None", ","...
.. versionadded:: 2014.1.0 .. versionchanged:: 2016.11.0 This state has been rewritten. Some arguments are new to this release and will not be available in the 2016.3 release cycle (and earlier). Additionally, the **ZIP Archive Handling** section below applies specifically to the 2016.11.0 release (and newer). Ensure that an archive is extracted to a specific directory. .. important:: **Changes for 2016.11.0** In earlier releases, this state would rely on the ``if_missing`` argument to determine whether or not the archive needed to be extracted. When this argument was not passed, then the state would just assume ``if_missing`` is the same as the ``name`` argument (i.e. the parent directory into which the archive would be extracted). This caused a number of annoyances. One such annoyance was the need to know beforehand a path that would result from the extraction of the archive, and setting ``if_missing`` to that directory, like so: .. code-block:: yaml extract_myapp: archive.extracted: - name: /var/www - source: salt://apps/src/myapp-16.2.4.tar.gz - user: www - group: www - if_missing: /var/www/myapp-16.2.4 If ``/var/www`` already existed, this would effectively make ``if_missing`` a required argument, just to get Salt to extract the archive. Some users worked around this by adding the top-level directory of the archive to the end of the ``name`` argument, and then used ``--strip`` or ``--strip-components`` to remove that top-level dir when extracting: .. code-block:: yaml extract_myapp: archive.extracted: - name: /var/www/myapp-16.2.4 - source: salt://apps/src/myapp-16.2.4.tar.gz - user: www - group: www With the rewrite for 2016.11.0, these workarounds are no longer necessary. ``if_missing`` is still a supported argument, but it is no longer required. The equivalent SLS in 2016.11.0 would be: .. code-block:: yaml extract_myapp: archive.extracted: - name: /var/www - source: salt://apps/src/myapp-16.2.4.tar.gz - user: www - group: www Salt now uses a function called :py:func:`archive.list <salt.modules.archive.list>` to get a list of files/directories in the archive. Using this information, the state can now check the minion to see if any paths are missing, and know whether or not the archive needs to be extracted. This makes the ``if_missing`` argument unnecessary in most use cases. .. important:: **ZIP Archive Handling** *Note: this information applies to 2016.11.0 and later.* Salt has two different functions for extracting ZIP archives: 1. :py:func:`archive.unzip <salt.modules.archive.unzip>`, which uses Python's zipfile_ module to extract ZIP files. 2. :py:func:`archive.cmd_unzip <salt.modules.archive.cmd_unzip>`, which uses the ``unzip`` CLI command to extract ZIP files. Salt will prefer the use of :py:func:`archive.cmd_unzip <salt.modules.archive.cmd_unzip>` when CLI options are specified (via the ``options`` argument), and will otherwise prefer the :py:func:`archive.unzip <salt.modules.archive.unzip>` function. Use of :py:func:`archive.cmd_unzip <salt.modules.archive.cmd_unzip>` can be forced however by setting the ``use_cmd_unzip`` argument to ``True``. By contrast, setting this argument to ``False`` will force usage of :py:func:`archive.unzip <salt.modules.archive.unzip>`. For example: .. code-block:: yaml /var/www: archive.extracted: - source: salt://foo/bar/myapp.zip - use_cmd_unzip: True When ``use_cmd_unzip`` is omitted, Salt will choose which extraction function to use based on the source archive and the arguments passed to the state. When in doubt, simply do not set this argument; it is provided as a means of overriding the logic Salt uses to decide which function to use. There are differences in the features available in both extraction functions. These are detailed below. - *Command-line options* (only supported by :py:func:`archive.cmd_unzip <salt.modules.archive.cmd_unzip>`) - When the ``options`` argument is used, :py:func:`archive.cmd_unzip <salt.modules.archive.cmd_unzip>` is the only function that can be used to extract the archive. Therefore, if ``use_cmd_unzip`` is specified and set to ``False``, and ``options`` is also set, the state will not proceed. - *Permissions* - Due to an `upstream bug in Python`_, permissions are not preserved when the zipfile_ module is used to extract an archive. As of the 2016.11.0 release, :py:func:`archive.unzip <salt.modules.archive.unzip>` (as well as this state) has an ``extract_perms`` argument which, when set to ``True`` (the default), will attempt to match the permissions of the extracted files/directories to those defined within the archive. To disable this functionality and have the state not attempt to preserve the permissions from the ZIP archive, set ``extract_perms`` to ``False``: .. code-block:: yaml /var/www: archive.extracted: - source: salt://foo/bar/myapp.zip - extract_perms: False .. _`upstream bug in Python`: https://bugs.python.org/issue15795 name Directory into which the archive should be extracted source Archive to be extracted .. note:: This argument uses the same syntax as its counterpart in the :py:func:`file.managed <salt.states.file.managed>` state. source_hash Hash of source file, or file with list of hash-to-file mappings .. note:: This argument uses the same syntax as its counterpart in the :py:func:`file.managed <salt.states.file.managed>` state. .. versionchanged:: 2016.11.0 If this argument specifies the hash itself, instead of a URI to a file containing hashes, the hash type can now be omitted and Salt will determine the hash type based on the length of the hash. For example, both of the below states are now valid, while before only the second one would be: .. code-block:: yaml foo_app: archive.extracted: - name: /var/www - source: https://mydomain.tld/foo.tar.gz - source_hash: 3360db35e682f1c5f9c58aa307de16d41361618c bar_app: archive.extracted: - name: /var/www - source: https://mydomain.tld/bar.tar.gz - source_hash: sha1=5edb7d584b82ddcbf76e311601f5d4442974aaa5 source_hash_name When ``source_hash`` refers to a hash file, Salt will try to find the correct hash by matching the filename part of the ``source`` URI. When managing a file with a ``source`` of ``salt://files/foo.tar.gz``, then the following line in a hash file would match: .. code-block:: text acbd18db4cc2f85cedef654fccc4a4d8 foo.tar.gz This line would also match: .. code-block:: text acbd18db4cc2f85cedef654fccc4a4d8 ./dir1/foo.tar.gz However, sometimes a hash file will include multiple similar paths: .. code-block:: text 37b51d194a7513e45b56f6524f2d51f2 ./dir1/foo.txt acbd18db4cc2f85cedef654fccc4a4d8 ./dir2/foo.txt 73feffa4b7f6bb68e44cf984c85f6e88 ./dir3/foo.txt In cases like this, Salt may match the incorrect hash. This argument can be used to tell Salt which filename to match, to ensure that the correct hash is identified. For example: .. code-block:: yaml /var/www: archive.extracted: - source: https://mydomain.tld/dir2/foo.tar.gz - source_hash: https://mydomain.tld/hashes - source_hash_name: ./dir2/foo.tar.gz .. note:: This argument must contain the full filename entry from the checksum file, as this argument is meant to disambiguate matches for multiple files that have the same basename. So, in the example above, simply using ``foo.txt`` would not match. .. versionadded:: 2016.11.0 source_hash_update : False Set this to ``True`` if archive should be extracted if source_hash has changed. This would extract regardless of the ``if_missing`` parameter. Note that this is only checked if the ``source`` value has not changed. If it has (e.g. to increment a version number in the path) then the archive will not be extracted even if the hash has changed. .. versionadded:: 2016.3.0 skip_verify : False If ``True``, hash verification of remote file sources (``http://``, ``https://``, ``ftp://``) will be skipped, and the ``source_hash`` argument will be ignored. .. versionadded:: 2016.3.4 keep_source : True For ``source`` archives not local to the minion (i.e. from the Salt fileserver or a remote source such as ``http(s)`` or ``ftp``), Salt will need to download the archive to the minion cache before they can be extracted. To remove the downloaded archive after extraction, set this argument to ``False``. .. versionadded:: 2017.7.3 keep : True Same as ``keep_source``, kept for backward-compatibility. .. note:: If both ``keep_source`` and ``keep`` are used, ``keep`` will be ignored. password **For ZIP archives only.** Password used for extraction. .. versionadded:: 2016.3.0 .. versionchanged:: 2016.11.0 The newly-added :py:func:`archive.is_encrypted <salt.modules.archive.is_encrypted>` function will be used to determine if the archive is password-protected. If it is, then the ``password`` argument will be required for the state to proceed. options **For tar and zip archives only.** This option can be used to specify a string of additional arguments to pass to the tar/zip command. If this argument is not used, then the minion will attempt to use Python's native tarfile_/zipfile_ support to extract it. For zip archives, this argument is mostly used to overwrite existing files with ``o``. Using this argument means that the ``tar`` or ``unzip`` command will be used, which is less platform-independent, so keep this in mind when using this option; the CLI options must be valid options for the ``tar``/``unzip`` implementation on the minion's OS. .. versionadded:: 2016.11.0 .. versionchanged:: 2015.8.11,2016.3.2 XZ-compressed tar archives no longer require ``J`` to manually be set in the ``options``, they are now detected automatically and decompressed using the xz_ CLI command and extracted using ``tar xvf``. This is a more platform-independent solution, as not all tar implementations support the ``J`` argument for extracting archives. .. note:: For tar archives, main operators like ``-x``, ``--extract``, ``--get``, ``-c`` and ``-f``/``--file`` should *not* be used here. list_options **For tar archives only.** This state uses :py:func:`archive.list <salt.modules.archive.list_>` to discover the contents of the source archive so that it knows which file paths should exist on the minion if the archive has already been extracted. For the vast majority of tar archives, :py:func:`archive.list <salt.modules.archive.list_>` "just works". Archives compressed using gzip, bzip2, and xz/lzma (with the help of the xz_ CLI command) are supported automatically. However, for archives compressed using other compression types, CLI options must be passed to :py:func:`archive.list <salt.modules.archive.list_>`. This argument will be passed through to :py:func:`archive.list <salt.modules.archive.list_>` as its ``options`` argument, to allow it to successfully list the archive's contents. For the vast majority of archives, this argument should not need to be used, it should only be needed in cases where the state fails with an error stating that the archive's contents could not be listed. .. versionadded:: 2016.11.0 force : False If a path that should be occupied by a file in the extracted result is instead a directory (or vice-versa), the state will fail. Set this argument to ``True`` to force these paths to be removed in order to allow the archive to be extracted. .. warning:: Use this option *very* carefully. .. versionadded:: 2016.11.0 overwrite : False Set this to ``True`` to force the archive to be extracted. This is useful for cases where the filenames/directories have not changed, but the content of the files have. .. versionadded:: 2016.11.1 clean : False Set this to ``True`` to remove any top-level files and recursively remove any top-level directory paths before extracting. .. note:: Files will only be cleaned first if extracting the archive is deemed necessary, either by paths missing on the minion, or if ``overwrite`` is set to ``True``. .. versionadded:: 2016.11.1 user The user to own each extracted file. Not available on Windows. .. versionadded:: 2015.8.0 .. versionchanged:: 2016.3.0 When used in combination with ``if_missing``, ownership will only be enforced if ``if_missing`` is a directory. .. versionchanged:: 2016.11.0 Ownership will be enforced only on the file/directory paths found by running :py:func:`archive.list <salt.modules.archive.list_>` on the source archive. An alternative root directory on which to enforce ownership can be specified using the ``enforce_ownership_on`` argument. group The group to own each extracted file. Not available on Windows. .. versionadded:: 2015.8.0 .. versionchanged:: 2016.3.0 When used in combination with ``if_missing``, ownership will only be enforced if ``if_missing`` is a directory. .. versionchanged:: 2016.11.0 Ownership will be enforced only on the file/directory paths found by running :py:func:`archive.list <salt.modules.archive.list_>` on the source archive. An alternative root directory on which to enforce ownership can be specified using the ``enforce_ownership_on`` argument. if_missing If specified, this path will be checked, and if it exists then the archive will not be extracted. This path can be either a directory or a file, so this option can also be used to check for a semaphore file and conditionally skip extraction. .. versionchanged:: 2016.3.0 When used in combination with either ``user`` or ``group``, ownership will only be enforced when ``if_missing`` is a directory. .. versionchanged:: 2016.11.0 Ownership enforcement is no longer tied to this argument, it is simply checked for existence and extraction will be skipped if if is present. trim_output : False Useful for archives with many files in them. This can either be set to ``True`` (in which case only the first 100 files extracted will be in the state results), or it can be set to an integer for more exact control over the max number of files to include in the state results. .. versionadded:: 2016.3.0 use_cmd_unzip : False Set to ``True`` for zip files to force usage of the :py:func:`archive.cmd_unzip <salt.modules.archive.cmd_unzip>` function to extract. .. versionadded:: 2016.11.0 extract_perms : True **For ZIP archives only.** When using :py:func:`archive.unzip <salt.modules.archive.unzip>` to extract ZIP archives, Salt works around an `upstream bug in Python`_ to set the permissions on extracted files/directories to match those encoded into the ZIP archive. Set this argument to ``False`` to skip this workaround. .. versionadded:: 2016.11.0 enforce_toplevel : True This option will enforce a single directory at the top level of the source archive, to prevent extracting a 'tar-bomb'. Set this argument to ``False`` to allow archives with files (or multiple directories) at the top level to be extracted. .. versionadded:: 2016.11.0 enforce_ownership_on When ``user`` or ``group`` is specified, Salt will default to enforcing permissions on the file/directory paths detected by running :py:func:`archive.list <salt.modules.archive.list_>` on the source archive. Use this argument to specify an alternate directory on which ownership should be enforced. .. note:: This path must be within the path specified by the ``name`` argument. .. versionadded:: 2016.11.0 archive_format One of ``tar``, ``zip``, or ``rar``. .. versionchanged:: 2016.11.0 If omitted, the archive format will be guessed based on the value of the ``source`` argument. If the minion is running a release older than 2016.11.0, this option is required. .. _tarfile: https://docs.python.org/2/library/tarfile.html .. _zipfile: https://docs.python.org/2/library/zipfile.html .. _xz: http://tukaani.org/xz/ **Examples** 1. tar with lmza (i.e. xz) compression: .. code-block:: yaml graylog2-server: archive.extracted: - name: /opt/ - source: https://github.com/downloads/Graylog2/graylog2-server/graylog2-server-0.9.6p1.tar.lzma - source_hash: md5=499ae16dcae71eeb7c3a30c75ea7a1a6 2. tar archive with flag for verbose output, and enforcement of user/group ownership: .. code-block:: yaml graylog2-server: archive.extracted: - name: /opt/ - source: https://github.com/downloads/Graylog2/graylog2-server/graylog2-server-0.9.6p1.tar.gz - source_hash: md5=499ae16dcae71eeb7c3a30c75ea7a1a6 - options: v - user: foo - group: foo 3. tar archive, with ``source_hash_update`` set to ``True`` to prevent state from attempting extraction unless the ``source_hash`` differs from the previous time the archive was extracted: .. code-block:: yaml graylog2-server: archive.extracted: - name: /opt/ - source: https://github.com/downloads/Graylog2/graylog2-server/graylog2-server-0.9.6p1.tar.lzma - source_hash: md5=499ae16dcae71eeb7c3a30c75ea7a1a6 - source_hash_update: True
[ "..", "versionadded", "::", "2014", ".", "1", ".", "0", "..", "versionchanged", "::", "2016", ".", "11", ".", "0", "This", "state", "has", "been", "rewritten", ".", "Some", "arguments", "are", "new", "to", "this", "release", "and", "will", "not", "be",...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/archive.py#L174-L1551
train
saltstack/salt
salt/modules/win_firewall.py
get_config
def get_config(): ''' Get the status of all the firewall profiles Returns: dict: A dictionary of all profiles on the system Raises: CommandExecutionError: If the command fails CLI Example: .. code-block:: bash salt '*' firewall.get_config ''' profiles = {} curr = None cmd = ['netsh', 'advfirewall', 'show', 'allprofiles'] ret = __salt__['cmd.run_all'](cmd, python_shell=False, ignore_retcode=True) if ret['retcode'] != 0: raise CommandExecutionError(ret['stdout']) # There may be some problems with this depending on how `netsh` is localized # It's looking for lines that contain `Profile Settings` or start with # `State` which may be different in different localizations for line in ret['stdout'].splitlines(): if not curr: tmp = re.search('(.*) Profile Settings:', line) if tmp: curr = tmp.group(1) elif line.startswith('State'): profiles[curr] = line.split()[1] == 'ON' curr = None return profiles
python
def get_config(): ''' Get the status of all the firewall profiles Returns: dict: A dictionary of all profiles on the system Raises: CommandExecutionError: If the command fails CLI Example: .. code-block:: bash salt '*' firewall.get_config ''' profiles = {} curr = None cmd = ['netsh', 'advfirewall', 'show', 'allprofiles'] ret = __salt__['cmd.run_all'](cmd, python_shell=False, ignore_retcode=True) if ret['retcode'] != 0: raise CommandExecutionError(ret['stdout']) # There may be some problems with this depending on how `netsh` is localized # It's looking for lines that contain `Profile Settings` or start with # `State` which may be different in different localizations for line in ret['stdout'].splitlines(): if not curr: tmp = re.search('(.*) Profile Settings:', line) if tmp: curr = tmp.group(1) elif line.startswith('State'): profiles[curr] = line.split()[1] == 'ON' curr = None return profiles
[ "def", "get_config", "(", ")", ":", "profiles", "=", "{", "}", "curr", "=", "None", "cmd", "=", "[", "'netsh'", ",", "'advfirewall'", ",", "'show'", ",", "'allprofiles'", "]", "ret", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "cmd", ",", "python_...
Get the status of all the firewall profiles Returns: dict: A dictionary of all profiles on the system Raises: CommandExecutionError: If the command fails CLI Example: .. code-block:: bash salt '*' firewall.get_config
[ "Get", "the", "status", "of", "all", "the", "firewall", "profiles" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_firewall.py#L29-L65
train
saltstack/salt
salt/modules/win_firewall.py
enable
def enable(profile='allprofiles'): ''' .. versionadded:: 2015.5.0 Enable firewall profile Args: profile (Optional[str]): The name of the profile to enable. Default is ``allprofiles``. Valid options are: - allprofiles - domainprofile - privateprofile - publicprofile Returns: bool: True if successful Raises: CommandExecutionError: If the command fails CLI Example: .. code-block:: bash salt '*' firewall.enable ''' cmd = ['netsh', 'advfirewall', 'set', profile, 'state', 'on'] ret = __salt__['cmd.run_all'](cmd, python_shell=False, ignore_retcode=True) if ret['retcode'] != 0: raise CommandExecutionError(ret['stdout']) return True
python
def enable(profile='allprofiles'): ''' .. versionadded:: 2015.5.0 Enable firewall profile Args: profile (Optional[str]): The name of the profile to enable. Default is ``allprofiles``. Valid options are: - allprofiles - domainprofile - privateprofile - publicprofile Returns: bool: True if successful Raises: CommandExecutionError: If the command fails CLI Example: .. code-block:: bash salt '*' firewall.enable ''' cmd = ['netsh', 'advfirewall', 'set', profile, 'state', 'on'] ret = __salt__['cmd.run_all'](cmd, python_shell=False, ignore_retcode=True) if ret['retcode'] != 0: raise CommandExecutionError(ret['stdout']) return True
[ "def", "enable", "(", "profile", "=", "'allprofiles'", ")", ":", "cmd", "=", "[", "'netsh'", ",", "'advfirewall'", ",", "'set'", ",", "profile", ",", "'state'", ",", "'on'", "]", "ret", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "cmd", ",", "pyth...
.. versionadded:: 2015.5.0 Enable firewall profile Args: profile (Optional[str]): The name of the profile to enable. Default is ``allprofiles``. Valid options are: - allprofiles - domainprofile - privateprofile - publicprofile Returns: bool: True if successful Raises: CommandExecutionError: If the command fails CLI Example: .. code-block:: bash salt '*' firewall.enable
[ "..", "versionadded", "::", "2015", ".", "5", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_firewall.py#L101-L133
train
saltstack/salt
salt/modules/win_firewall.py
get_rule
def get_rule(name='all'): ''' .. versionadded:: 2015.5.0 Display all matching rules as specified by name Args: name (Optional[str]): The full name of the rule. ``all`` will return all rules. Default is ``all`` Returns: dict: A dictionary of all rules or rules that match the name exactly Raises: CommandExecutionError: If the command fails CLI Example: .. code-block:: bash salt '*' firewall.get_rule 'MyAppPort' ''' cmd = ['netsh', 'advfirewall', 'firewall', 'show', 'rule', 'name={0}'.format(name)] ret = __salt__['cmd.run_all'](cmd, python_shell=False, ignore_retcode=True) if ret['retcode'] != 0: raise CommandExecutionError(ret['stdout']) return {name: ret['stdout']}
python
def get_rule(name='all'): ''' .. versionadded:: 2015.5.0 Display all matching rules as specified by name Args: name (Optional[str]): The full name of the rule. ``all`` will return all rules. Default is ``all`` Returns: dict: A dictionary of all rules or rules that match the name exactly Raises: CommandExecutionError: If the command fails CLI Example: .. code-block:: bash salt '*' firewall.get_rule 'MyAppPort' ''' cmd = ['netsh', 'advfirewall', 'firewall', 'show', 'rule', 'name={0}'.format(name)] ret = __salt__['cmd.run_all'](cmd, python_shell=False, ignore_retcode=True) if ret['retcode'] != 0: raise CommandExecutionError(ret['stdout']) return {name: ret['stdout']}
[ "def", "get_rule", "(", "name", "=", "'all'", ")", ":", "cmd", "=", "[", "'netsh'", ",", "'advfirewall'", ",", "'firewall'", ",", "'show'", ",", "'rule'", ",", "'name={0}'", ".", "format", "(", "name", ")", "]", "ret", "=", "__salt__", "[", "'cmd.run_a...
.. versionadded:: 2015.5.0 Display all matching rules as specified by name Args: name (Optional[str]): The full name of the rule. ``all`` will return all rules. Default is ``all`` Returns: dict: A dictionary of all rules or rules that match the name exactly Raises: CommandExecutionError: If the command fails CLI Example: .. code-block:: bash salt '*' firewall.get_rule 'MyAppPort'
[ "..", "versionadded", "::", "2015", ".", "5", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_firewall.py#L136-L164
train
saltstack/salt
salt/modules/win_firewall.py
add_rule
def add_rule(name, localport, protocol='tcp', action='allow', dir='in', remoteip='any'): ''' .. versionadded:: 2015.5.0 Add a new inbound or outbound rule to the firewall policy Args: name (str): The name of the rule. Must be unique and cannot be "all". Required. localport (int): The port the rule applies to. Must be a number between 0 and 65535. Can be a range. Can specify multiple ports separated by commas. Required. protocol (Optional[str]): The protocol. Can be any of the following: - A number between 0 and 255 - icmpv4 - icmpv6 - tcp - udp - any action (Optional[str]): The action the rule performs. Can be any of the following: - allow - block - bypass dir (Optional[str]): The direction. Can be ``in`` or ``out``. remoteip (Optional [str]): The remote IP. Can be any of the following: - any - localsubnet - dns - dhcp - wins - defaultgateway - Any valid IPv4 address (192.168.0.12) - Any valid IPv6 address (2002:9b3b:1a31:4:208:74ff:fe39:6c43) - Any valid subnet (192.168.1.0/24) - Any valid range of IP addresses (192.168.0.1-192.168.0.12) - A list of valid IP addresses Can be combinations of the above separated by commas. Returns: bool: True if successful Raises: CommandExecutionError: If the command fails CLI Example: .. code-block:: bash salt '*' firewall.add_rule 'test' '8080' 'tcp' salt '*' firewall.add_rule 'test' '1' 'icmpv4' salt '*' firewall.add_rule 'test_remote_ip' '8000' 'tcp' 'allow' 'in' '192.168.0.1' ''' cmd = ['netsh', 'advfirewall', 'firewall', 'add', 'rule', 'name={0}'.format(name), 'protocol={0}'.format(protocol), 'dir={0}'.format(dir), 'action={0}'.format(action), 'remoteip={0}'.format(remoteip)] if protocol is None \ or ('icmpv4' not in protocol and 'icmpv6' not in protocol): cmd.append('localport={0}'.format(localport)) ret = __salt__['cmd.run_all'](cmd, python_shell=False, ignore_retcode=True) if ret['retcode'] != 0: raise CommandExecutionError(ret['stdout']) return True
python
def add_rule(name, localport, protocol='tcp', action='allow', dir='in', remoteip='any'): ''' .. versionadded:: 2015.5.0 Add a new inbound or outbound rule to the firewall policy Args: name (str): The name of the rule. Must be unique and cannot be "all". Required. localport (int): The port the rule applies to. Must be a number between 0 and 65535. Can be a range. Can specify multiple ports separated by commas. Required. protocol (Optional[str]): The protocol. Can be any of the following: - A number between 0 and 255 - icmpv4 - icmpv6 - tcp - udp - any action (Optional[str]): The action the rule performs. Can be any of the following: - allow - block - bypass dir (Optional[str]): The direction. Can be ``in`` or ``out``. remoteip (Optional [str]): The remote IP. Can be any of the following: - any - localsubnet - dns - dhcp - wins - defaultgateway - Any valid IPv4 address (192.168.0.12) - Any valid IPv6 address (2002:9b3b:1a31:4:208:74ff:fe39:6c43) - Any valid subnet (192.168.1.0/24) - Any valid range of IP addresses (192.168.0.1-192.168.0.12) - A list of valid IP addresses Can be combinations of the above separated by commas. Returns: bool: True if successful Raises: CommandExecutionError: If the command fails CLI Example: .. code-block:: bash salt '*' firewall.add_rule 'test' '8080' 'tcp' salt '*' firewall.add_rule 'test' '1' 'icmpv4' salt '*' firewall.add_rule 'test_remote_ip' '8000' 'tcp' 'allow' 'in' '192.168.0.1' ''' cmd = ['netsh', 'advfirewall', 'firewall', 'add', 'rule', 'name={0}'.format(name), 'protocol={0}'.format(protocol), 'dir={0}'.format(dir), 'action={0}'.format(action), 'remoteip={0}'.format(remoteip)] if protocol is None \ or ('icmpv4' not in protocol and 'icmpv6' not in protocol): cmd.append('localport={0}'.format(localport)) ret = __salt__['cmd.run_all'](cmd, python_shell=False, ignore_retcode=True) if ret['retcode'] != 0: raise CommandExecutionError(ret['stdout']) return True
[ "def", "add_rule", "(", "name", ",", "localport", ",", "protocol", "=", "'tcp'", ",", "action", "=", "'allow'", ",", "dir", "=", "'in'", ",", "remoteip", "=", "'any'", ")", ":", "cmd", "=", "[", "'netsh'", ",", "'advfirewall'", ",", "'firewall'", ",", ...
.. versionadded:: 2015.5.0 Add a new inbound or outbound rule to the firewall policy Args: name (str): The name of the rule. Must be unique and cannot be "all". Required. localport (int): The port the rule applies to. Must be a number between 0 and 65535. Can be a range. Can specify multiple ports separated by commas. Required. protocol (Optional[str]): The protocol. Can be any of the following: - A number between 0 and 255 - icmpv4 - icmpv6 - tcp - udp - any action (Optional[str]): The action the rule performs. Can be any of the following: - allow - block - bypass dir (Optional[str]): The direction. Can be ``in`` or ``out``. remoteip (Optional [str]): The remote IP. Can be any of the following: - any - localsubnet - dns - dhcp - wins - defaultgateway - Any valid IPv4 address (192.168.0.12) - Any valid IPv6 address (2002:9b3b:1a31:4:208:74ff:fe39:6c43) - Any valid subnet (192.168.1.0/24) - Any valid range of IP addresses (192.168.0.1-192.168.0.12) - A list of valid IP addresses Can be combinations of the above separated by commas. Returns: bool: True if successful Raises: CommandExecutionError: If the command fails CLI Example: .. code-block:: bash salt '*' firewall.add_rule 'test' '8080' 'tcp' salt '*' firewall.add_rule 'test' '1' 'icmpv4' salt '*' firewall.add_rule 'test_remote_ip' '8000' 'tcp' 'allow' 'in' '192.168.0.1'
[ "..", "versionadded", "::", "2015", ".", "5", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_firewall.py#L167-L246
train
saltstack/salt
salt/modules/win_firewall.py
delete_rule
def delete_rule(name=None, localport=None, protocol=None, dir=None, remoteip=None): ''' .. versionadded:: 2015.8.0 Delete an existing firewall rule identified by name and optionally by ports, protocols, direction, and remote IP. Args: name (str): The name of the rule to delete. If the name ``all`` is used you must specify additional parameters. localport (Optional[str]): The port of the rule. If protocol is not specified, protocol will be set to ``tcp`` protocol (Optional[str]): The protocol of the rule. Default is ``tcp`` when ``localport`` is specified dir (Optional[str]): The direction of the rule. remoteip (Optional[str]): The remote IP of the rule. Returns: bool: True if successful Raises: CommandExecutionError: If the command fails CLI Example: .. code-block:: bash # Delete incoming tcp port 8080 in the rule named 'test' salt '*' firewall.delete_rule 'test' '8080' 'tcp' 'in' # Delete the incoming tcp port 8000 from 192.168.0.1 in the rule named # 'test_remote_ip' salt '*' firewall.delete_rule 'test_remote_ip' '8000' 'tcp' 'in' '192.168.0.1' # Delete all rules for local port 80: salt '*' firewall.delete_rule all 80 tcp # Delete a rule called 'allow80': salt '*' firewall.delete_rule allow80 ''' cmd = ['netsh', 'advfirewall', 'firewall', 'delete', 'rule'] if name: cmd.append('name={0}'.format(name)) if protocol: cmd.append('protocol={0}'.format(protocol)) if dir: cmd.append('dir={0}'.format(dir)) if remoteip: cmd.append('remoteip={0}'.format(remoteip)) if protocol is None \ or ('icmpv4' not in protocol and 'icmpv6' not in protocol): if localport: if not protocol: cmd.append('protocol=tcp') cmd.append('localport={0}'.format(localport)) ret = __salt__['cmd.run_all'](cmd, python_shell=False, ignore_retcode=True) if ret['retcode'] != 0: raise CommandExecutionError(ret['stdout']) return True
python
def delete_rule(name=None, localport=None, protocol=None, dir=None, remoteip=None): ''' .. versionadded:: 2015.8.0 Delete an existing firewall rule identified by name and optionally by ports, protocols, direction, and remote IP. Args: name (str): The name of the rule to delete. If the name ``all`` is used you must specify additional parameters. localport (Optional[str]): The port of the rule. If protocol is not specified, protocol will be set to ``tcp`` protocol (Optional[str]): The protocol of the rule. Default is ``tcp`` when ``localport`` is specified dir (Optional[str]): The direction of the rule. remoteip (Optional[str]): The remote IP of the rule. Returns: bool: True if successful Raises: CommandExecutionError: If the command fails CLI Example: .. code-block:: bash # Delete incoming tcp port 8080 in the rule named 'test' salt '*' firewall.delete_rule 'test' '8080' 'tcp' 'in' # Delete the incoming tcp port 8000 from 192.168.0.1 in the rule named # 'test_remote_ip' salt '*' firewall.delete_rule 'test_remote_ip' '8000' 'tcp' 'in' '192.168.0.1' # Delete all rules for local port 80: salt '*' firewall.delete_rule all 80 tcp # Delete a rule called 'allow80': salt '*' firewall.delete_rule allow80 ''' cmd = ['netsh', 'advfirewall', 'firewall', 'delete', 'rule'] if name: cmd.append('name={0}'.format(name)) if protocol: cmd.append('protocol={0}'.format(protocol)) if dir: cmd.append('dir={0}'.format(dir)) if remoteip: cmd.append('remoteip={0}'.format(remoteip)) if protocol is None \ or ('icmpv4' not in protocol and 'icmpv6' not in protocol): if localport: if not protocol: cmd.append('protocol=tcp') cmd.append('localport={0}'.format(localport)) ret = __salt__['cmd.run_all'](cmd, python_shell=False, ignore_retcode=True) if ret['retcode'] != 0: raise CommandExecutionError(ret['stdout']) return True
[ "def", "delete_rule", "(", "name", "=", "None", ",", "localport", "=", "None", ",", "protocol", "=", "None", ",", "dir", "=", "None", ",", "remoteip", "=", "None", ")", ":", "cmd", "=", "[", "'netsh'", ",", "'advfirewall'", ",", "'firewall'", ",", "'...
.. versionadded:: 2015.8.0 Delete an existing firewall rule identified by name and optionally by ports, protocols, direction, and remote IP. Args: name (str): The name of the rule to delete. If the name ``all`` is used you must specify additional parameters. localport (Optional[str]): The port of the rule. If protocol is not specified, protocol will be set to ``tcp`` protocol (Optional[str]): The protocol of the rule. Default is ``tcp`` when ``localport`` is specified dir (Optional[str]): The direction of the rule. remoteip (Optional[str]): The remote IP of the rule. Returns: bool: True if successful Raises: CommandExecutionError: If the command fails CLI Example: .. code-block:: bash # Delete incoming tcp port 8080 in the rule named 'test' salt '*' firewall.delete_rule 'test' '8080' 'tcp' 'in' # Delete the incoming tcp port 8000 from 192.168.0.1 in the rule named # 'test_remote_ip' salt '*' firewall.delete_rule 'test_remote_ip' '8000' 'tcp' 'in' '192.168.0.1' # Delete all rules for local port 80: salt '*' firewall.delete_rule all 80 tcp # Delete a rule called 'allow80': salt '*' firewall.delete_rule allow80
[ "..", "versionadded", "::", "2015", ".", "8", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_firewall.py#L249-L319
train
saltstack/salt
salt/modules/win_firewall.py
get_settings
def get_settings(profile, section, store='local'): ''' Get the firewall property from the specified profile in the specified store as returned by ``netsh advfirewall``. .. versionadded:: 2018.3.4 .. versionadded:: 2019.2.0 Args: profile (str): The firewall profile to query. Valid options are: - domain - public - private section (str): The property to query within the selected profile. Valid options are: - firewallpolicy : inbound/outbound behavior - logging : firewall logging settings - settings : firewall properties - state : firewalls state (on | off) store (str): The store to use. This is either the local firewall policy or the policy defined by local group policy. Valid options are: - lgpo - local Default is ``local`` Returns: dict: A dictionary containing the properties for the specified profile Raises: CommandExecutionError: If an error occurs ValueError: If the parameters are incorrect CLI Example: .. code-block:: bash # Get the inbound/outbound firewall settings for connections on the # local domain profile salt * win_firewall.get_settings domain firewallpolicy # Get the inbound/outbound firewall settings for connections on the # domain profile as defined by local group policy salt * win_firewall.get_settings domain firewallpolicy lgpo ''' return salt.utils.win_lgpo_netsh.get_settings(profile=profile, section=section, store=store)
python
def get_settings(profile, section, store='local'): ''' Get the firewall property from the specified profile in the specified store as returned by ``netsh advfirewall``. .. versionadded:: 2018.3.4 .. versionadded:: 2019.2.0 Args: profile (str): The firewall profile to query. Valid options are: - domain - public - private section (str): The property to query within the selected profile. Valid options are: - firewallpolicy : inbound/outbound behavior - logging : firewall logging settings - settings : firewall properties - state : firewalls state (on | off) store (str): The store to use. This is either the local firewall policy or the policy defined by local group policy. Valid options are: - lgpo - local Default is ``local`` Returns: dict: A dictionary containing the properties for the specified profile Raises: CommandExecutionError: If an error occurs ValueError: If the parameters are incorrect CLI Example: .. code-block:: bash # Get the inbound/outbound firewall settings for connections on the # local domain profile salt * win_firewall.get_settings domain firewallpolicy # Get the inbound/outbound firewall settings for connections on the # domain profile as defined by local group policy salt * win_firewall.get_settings domain firewallpolicy lgpo ''' return salt.utils.win_lgpo_netsh.get_settings(profile=profile, section=section, store=store)
[ "def", "get_settings", "(", "profile", ",", "section", ",", "store", "=", "'local'", ")", ":", "return", "salt", ".", "utils", ".", "win_lgpo_netsh", ".", "get_settings", "(", "profile", "=", "profile", ",", "section", "=", "section", ",", "store", "=", ...
Get the firewall property from the specified profile in the specified store as returned by ``netsh advfirewall``. .. versionadded:: 2018.3.4 .. versionadded:: 2019.2.0 Args: profile (str): The firewall profile to query. Valid options are: - domain - public - private section (str): The property to query within the selected profile. Valid options are: - firewallpolicy : inbound/outbound behavior - logging : firewall logging settings - settings : firewall properties - state : firewalls state (on | off) store (str): The store to use. This is either the local firewall policy or the policy defined by local group policy. Valid options are: - lgpo - local Default is ``local`` Returns: dict: A dictionary containing the properties for the specified profile Raises: CommandExecutionError: If an error occurs ValueError: If the parameters are incorrect CLI Example: .. code-block:: bash # Get the inbound/outbound firewall settings for connections on the # local domain profile salt * win_firewall.get_settings domain firewallpolicy # Get the inbound/outbound firewall settings for connections on the # domain profile as defined by local group policy salt * win_firewall.get_settings domain firewallpolicy lgpo
[ "Get", "the", "firewall", "property", "from", "the", "specified", "profile", "in", "the", "specified", "store", "as", "returned", "by", "netsh", "advfirewall", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_firewall.py#L348-L404
train
saltstack/salt
salt/modules/win_firewall.py
get_all_settings
def get_all_settings(domain, store='local'): ''' Gets all the properties for the specified profile in the specified store .. versionadded:: 2018.3.4 .. versionadded:: 2019.2.0 Args: profile (str): The firewall profile to query. Valid options are: - domain - public - private store (str): The store to use. This is either the local firewall policy or the policy defined by local group policy. Valid options are: - lgpo - local Default is ``local`` Returns: dict: A dictionary containing the specified settings CLI Example: .. code-block:: bash # Get all firewall settings for connections on the domain profile salt * win_firewall.get_all_settings domain # Get all firewall settings for connections on the domain profile as # defined by local group policy salt * win_firewall.get_all_settings domain lgpo ''' return salt.utils.win_lgpo_netsh.get_all_settings(profile=domain, store=store)
python
def get_all_settings(domain, store='local'): ''' Gets all the properties for the specified profile in the specified store .. versionadded:: 2018.3.4 .. versionadded:: 2019.2.0 Args: profile (str): The firewall profile to query. Valid options are: - domain - public - private store (str): The store to use. This is either the local firewall policy or the policy defined by local group policy. Valid options are: - lgpo - local Default is ``local`` Returns: dict: A dictionary containing the specified settings CLI Example: .. code-block:: bash # Get all firewall settings for connections on the domain profile salt * win_firewall.get_all_settings domain # Get all firewall settings for connections on the domain profile as # defined by local group policy salt * win_firewall.get_all_settings domain lgpo ''' return salt.utils.win_lgpo_netsh.get_all_settings(profile=domain, store=store)
[ "def", "get_all_settings", "(", "domain", ",", "store", "=", "'local'", ")", ":", "return", "salt", ".", "utils", ".", "win_lgpo_netsh", ".", "get_all_settings", "(", "profile", "=", "domain", ",", "store", "=", "store", ")" ]
Gets all the properties for the specified profile in the specified store .. versionadded:: 2018.3.4 .. versionadded:: 2019.2.0 Args: profile (str): The firewall profile to query. Valid options are: - domain - public - private store (str): The store to use. This is either the local firewall policy or the policy defined by local group policy. Valid options are: - lgpo - local Default is ``local`` Returns: dict: A dictionary containing the specified settings CLI Example: .. code-block:: bash # Get all firewall settings for connections on the domain profile salt * win_firewall.get_all_settings domain # Get all firewall settings for connections on the domain profile as # defined by local group policy salt * win_firewall.get_all_settings domain lgpo
[ "Gets", "all", "the", "properties", "for", "the", "specified", "profile", "in", "the", "specified", "store" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_firewall.py#L407-L447
train
saltstack/salt
salt/modules/win_firewall.py
set_firewall_settings
def set_firewall_settings(profile, inbound=None, outbound=None, store='local'): ''' Set the firewall inbound/outbound settings for the specified profile and store .. versionadded:: 2018.3.4 .. versionadded:: 2019.2.0 Args: profile (str): The firewall profile to query. Valid options are: - domain - public - private inbound (str): The inbound setting. If ``None`` is passed, the setting will remain unchanged. Valid values are: - blockinbound - blockinboundalways - allowinbound - notconfigured Default is ``None`` outbound (str): The outbound setting. If ``None`` is passed, the setting will remain unchanged. Valid values are: - allowoutbound - blockoutbound - notconfigured Default is ``None`` store (str): The store to use. This is either the local firewall policy or the policy defined by local group policy. Valid options are: - lgpo - local Default is ``local`` Returns: bool: ``True`` if successful Raises: CommandExecutionError: If an error occurs ValueError: If the parameters are incorrect CLI Example: .. code-block:: bash # Set the inbound setting for the domain profile to block inbound # connections salt * firewall.set_firewall_settings domain='domain' inbound='blockinbound' # Set the outbound setting for the domain profile to allow outbound # connections salt * firewall.set_firewall_settings domain='domain' outbound='allowoutbound' # Set inbound/outbound settings for the domain profile in the group # policy to block inbound and allow outbound salt * firewall.set_firewall_settings domain='domain' inbound='blockinbound' outbound='allowoutbound' store='lgpo' ''' return salt.utils.win_lgpo_netsh.set_firewall_settings(profile=profile, inbound=inbound, outbound=outbound, store=store)
python
def set_firewall_settings(profile, inbound=None, outbound=None, store='local'): ''' Set the firewall inbound/outbound settings for the specified profile and store .. versionadded:: 2018.3.4 .. versionadded:: 2019.2.0 Args: profile (str): The firewall profile to query. Valid options are: - domain - public - private inbound (str): The inbound setting. If ``None`` is passed, the setting will remain unchanged. Valid values are: - blockinbound - blockinboundalways - allowinbound - notconfigured Default is ``None`` outbound (str): The outbound setting. If ``None`` is passed, the setting will remain unchanged. Valid values are: - allowoutbound - blockoutbound - notconfigured Default is ``None`` store (str): The store to use. This is either the local firewall policy or the policy defined by local group policy. Valid options are: - lgpo - local Default is ``local`` Returns: bool: ``True`` if successful Raises: CommandExecutionError: If an error occurs ValueError: If the parameters are incorrect CLI Example: .. code-block:: bash # Set the inbound setting for the domain profile to block inbound # connections salt * firewall.set_firewall_settings domain='domain' inbound='blockinbound' # Set the outbound setting for the domain profile to allow outbound # connections salt * firewall.set_firewall_settings domain='domain' outbound='allowoutbound' # Set inbound/outbound settings for the domain profile in the group # policy to block inbound and allow outbound salt * firewall.set_firewall_settings domain='domain' inbound='blockinbound' outbound='allowoutbound' store='lgpo' ''' return salt.utils.win_lgpo_netsh.set_firewall_settings(profile=profile, inbound=inbound, outbound=outbound, store=store)
[ "def", "set_firewall_settings", "(", "profile", ",", "inbound", "=", "None", ",", "outbound", "=", "None", ",", "store", "=", "'local'", ")", ":", "return", "salt", ".", "utils", ".", "win_lgpo_netsh", ".", "set_firewall_settings", "(", "profile", "=", "prof...
Set the firewall inbound/outbound settings for the specified profile and store .. versionadded:: 2018.3.4 .. versionadded:: 2019.2.0 Args: profile (str): The firewall profile to query. Valid options are: - domain - public - private inbound (str): The inbound setting. If ``None`` is passed, the setting will remain unchanged. Valid values are: - blockinbound - blockinboundalways - allowinbound - notconfigured Default is ``None`` outbound (str): The outbound setting. If ``None`` is passed, the setting will remain unchanged. Valid values are: - allowoutbound - blockoutbound - notconfigured Default is ``None`` store (str): The store to use. This is either the local firewall policy or the policy defined by local group policy. Valid options are: - lgpo - local Default is ``local`` Returns: bool: ``True`` if successful Raises: CommandExecutionError: If an error occurs ValueError: If the parameters are incorrect CLI Example: .. code-block:: bash # Set the inbound setting for the domain profile to block inbound # connections salt * firewall.set_firewall_settings domain='domain' inbound='blockinbound' # Set the outbound setting for the domain profile to allow outbound # connections salt * firewall.set_firewall_settings domain='domain' outbound='allowoutbound' # Set inbound/outbound settings for the domain profile in the group # policy to block inbound and allow outbound salt * firewall.set_firewall_settings domain='domain' inbound='blockinbound' outbound='allowoutbound' store='lgpo'
[ "Set", "the", "firewall", "inbound", "/", "outbound", "settings", "for", "the", "specified", "profile", "and", "store" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_firewall.py#L486-L559
train
saltstack/salt
salt/modules/win_firewall.py
set_logging_settings
def set_logging_settings(profile, setting, value, store='local'): r''' Configure logging settings for the Windows firewall. .. versionadded:: 2018.3.4 .. versionadded:: 2019.2.0 Args: profile (str): The firewall profile to configure. Valid options are: - domain - public - private setting (str): The logging setting to configure. Valid options are: - allowedconnections - droppedconnections - filename - maxfilesize value (str): The value to apply to the setting. Valid values are dependent upon the setting being configured. Valid options are: allowedconnections: - enable - disable - notconfigured droppedconnections: - enable - disable - notconfigured filename: - Full path and name of the firewall log file - notconfigured maxfilesize: - 1 - 32767 - notconfigured .. note:: ``notconfigured`` can only be used when using the lgpo store store (str): The store to use. This is either the local firewall policy or the policy defined by local group policy. Valid options are: - lgpo - local Default is ``local`` Returns: bool: ``True`` if successful Raises: CommandExecutionError: If an error occurs ValueError: If the parameters are incorrect CLI Example: .. code-block:: bash # Log allowed connections and set that in local group policy salt * firewall.set_logging_settings domain allowedconnections enable lgpo # Don't log dropped connections salt * firewall.set_logging_settings profile=private setting=droppedconnections value=disable # Set the location of the log file salt * firewall.set_logging_settings domain filename C:\windows\logs\firewall.log # You can also use environment variables salt * firewall.set_logging_settings domain filename %systemroot%\system32\LogFiles\Firewall\pfirewall.log # Set the max file size of the log to 2048 Kb salt * firewall.set_logging_settings domain maxfilesize 2048 ''' return salt.utils.win_lgpo_netsh.set_logging_settings(profile=profile, setting=setting, value=value, store=store)
python
def set_logging_settings(profile, setting, value, store='local'): r''' Configure logging settings for the Windows firewall. .. versionadded:: 2018.3.4 .. versionadded:: 2019.2.0 Args: profile (str): The firewall profile to configure. Valid options are: - domain - public - private setting (str): The logging setting to configure. Valid options are: - allowedconnections - droppedconnections - filename - maxfilesize value (str): The value to apply to the setting. Valid values are dependent upon the setting being configured. Valid options are: allowedconnections: - enable - disable - notconfigured droppedconnections: - enable - disable - notconfigured filename: - Full path and name of the firewall log file - notconfigured maxfilesize: - 1 - 32767 - notconfigured .. note:: ``notconfigured`` can only be used when using the lgpo store store (str): The store to use. This is either the local firewall policy or the policy defined by local group policy. Valid options are: - lgpo - local Default is ``local`` Returns: bool: ``True`` if successful Raises: CommandExecutionError: If an error occurs ValueError: If the parameters are incorrect CLI Example: .. code-block:: bash # Log allowed connections and set that in local group policy salt * firewall.set_logging_settings domain allowedconnections enable lgpo # Don't log dropped connections salt * firewall.set_logging_settings profile=private setting=droppedconnections value=disable # Set the location of the log file salt * firewall.set_logging_settings domain filename C:\windows\logs\firewall.log # You can also use environment variables salt * firewall.set_logging_settings domain filename %systemroot%\system32\LogFiles\Firewall\pfirewall.log # Set the max file size of the log to 2048 Kb salt * firewall.set_logging_settings domain maxfilesize 2048 ''' return salt.utils.win_lgpo_netsh.set_logging_settings(profile=profile, setting=setting, value=value, store=store)
[ "def", "set_logging_settings", "(", "profile", ",", "setting", ",", "value", ",", "store", "=", "'local'", ")", ":", "return", "salt", ".", "utils", ".", "win_lgpo_netsh", ".", "set_logging_settings", "(", "profile", "=", "profile", ",", "setting", "=", "set...
r''' Configure logging settings for the Windows firewall. .. versionadded:: 2018.3.4 .. versionadded:: 2019.2.0 Args: profile (str): The firewall profile to configure. Valid options are: - domain - public - private setting (str): The logging setting to configure. Valid options are: - allowedconnections - droppedconnections - filename - maxfilesize value (str): The value to apply to the setting. Valid values are dependent upon the setting being configured. Valid options are: allowedconnections: - enable - disable - notconfigured droppedconnections: - enable - disable - notconfigured filename: - Full path and name of the firewall log file - notconfigured maxfilesize: - 1 - 32767 - notconfigured .. note:: ``notconfigured`` can only be used when using the lgpo store store (str): The store to use. This is either the local firewall policy or the policy defined by local group policy. Valid options are: - lgpo - local Default is ``local`` Returns: bool: ``True`` if successful Raises: CommandExecutionError: If an error occurs ValueError: If the parameters are incorrect CLI Example: .. code-block:: bash # Log allowed connections and set that in local group policy salt * firewall.set_logging_settings domain allowedconnections enable lgpo # Don't log dropped connections salt * firewall.set_logging_settings profile=private setting=droppedconnections value=disable # Set the location of the log file salt * firewall.set_logging_settings domain filename C:\windows\logs\firewall.log # You can also use environment variables salt * firewall.set_logging_settings domain filename %systemroot%\system32\LogFiles\Firewall\pfirewall.log # Set the max file size of the log to 2048 Kb salt * firewall.set_logging_settings domain maxfilesize 2048
[ "r", "Configure", "logging", "settings", "for", "the", "Windows", "firewall", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_firewall.py#L562-L653
train
saltstack/salt
salt/modules/win_firewall.py
set_settings
def set_settings(profile, setting, value, store='local'): ''' Configure firewall settings. .. versionadded:: 2018.3.4 .. versionadded:: 2019.2.0 Args: profile (str): The firewall profile to configure. Valid options are: - domain - public - private setting (str): The firewall setting to configure. Valid options are: - localfirewallrules - localconsecrules - inboundusernotification - remotemanagement - unicastresponsetomulticast value (str): The value to apply to the setting. Valid options are - enable - disable - notconfigured .. note:: ``notconfigured`` can only be used when using the lgpo store store (str): The store to use. This is either the local firewall policy or the policy defined by local group policy. Valid options are: - lgpo - local Default is ``local`` Returns: bool: ``True`` if successful Raises: CommandExecutionError: If an error occurs ValueError: If the parameters are incorrect CLI Example: .. code-block:: bash # Merge local rules with those distributed through group policy salt * firewall.set_settings domain localfirewallrules enable # Allow remote management of Windows Firewall salt * firewall.set_settings domain remotemanagement enable ''' return salt.utils.win_lgpo_netsh.set_settings(profile=profile, setting=setting, value=value, store=store)
python
def set_settings(profile, setting, value, store='local'): ''' Configure firewall settings. .. versionadded:: 2018.3.4 .. versionadded:: 2019.2.0 Args: profile (str): The firewall profile to configure. Valid options are: - domain - public - private setting (str): The firewall setting to configure. Valid options are: - localfirewallrules - localconsecrules - inboundusernotification - remotemanagement - unicastresponsetomulticast value (str): The value to apply to the setting. Valid options are - enable - disable - notconfigured .. note:: ``notconfigured`` can only be used when using the lgpo store store (str): The store to use. This is either the local firewall policy or the policy defined by local group policy. Valid options are: - lgpo - local Default is ``local`` Returns: bool: ``True`` if successful Raises: CommandExecutionError: If an error occurs ValueError: If the parameters are incorrect CLI Example: .. code-block:: bash # Merge local rules with those distributed through group policy salt * firewall.set_settings domain localfirewallrules enable # Allow remote management of Windows Firewall salt * firewall.set_settings domain remotemanagement enable ''' return salt.utils.win_lgpo_netsh.set_settings(profile=profile, setting=setting, value=value, store=store)
[ "def", "set_settings", "(", "profile", ",", "setting", ",", "value", ",", "store", "=", "'local'", ")", ":", "return", "salt", ".", "utils", ".", "win_lgpo_netsh", ".", "set_settings", "(", "profile", "=", "profile", ",", "setting", "=", "setting", ",", ...
Configure firewall settings. .. versionadded:: 2018.3.4 .. versionadded:: 2019.2.0 Args: profile (str): The firewall profile to configure. Valid options are: - domain - public - private setting (str): The firewall setting to configure. Valid options are: - localfirewallrules - localconsecrules - inboundusernotification - remotemanagement - unicastresponsetomulticast value (str): The value to apply to the setting. Valid options are - enable - disable - notconfigured .. note:: ``notconfigured`` can only be used when using the lgpo store store (str): The store to use. This is either the local firewall policy or the policy defined by local group policy. Valid options are: - lgpo - local Default is ``local`` Returns: bool: ``True`` if successful Raises: CommandExecutionError: If an error occurs ValueError: If the parameters are incorrect CLI Example: .. code-block:: bash # Merge local rules with those distributed through group policy salt * firewall.set_settings domain localfirewallrules enable # Allow remote management of Windows Firewall salt * firewall.set_settings domain remotemanagement enable
[ "Configure", "firewall", "settings", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_firewall.py#L656-L720
train
saltstack/salt
salt/modules/win_firewall.py
set_state
def set_state(profile, state, store='local'): ''' Configure the firewall state. .. versionadded:: 2018.3.4 .. versionadded:: 2019.2.0 Args: profile (str): The firewall profile to configure. Valid options are: - domain - public - private state (str): The firewall state. Valid options are: - on - off - notconfigured .. note:: ``notconfigured`` can only be used when using the lgpo store store (str): The store to use. This is either the local firewall policy or the policy defined by local group policy. Valid options are: - lgpo - local Default is ``local`` Returns: bool: ``True`` if successful Raises: CommandExecutionError: If an error occurs ValueError: If the parameters are incorrect CLI Example: .. code-block:: bash # Turn the firewall off when the domain profile is active salt * firewall.set_state domain off # Turn the firewall on when the public profile is active and set that in # the local group policy salt * firewall.set_state public on lgpo ''' return salt.utils.win_lgpo_netsh.set_state(profile=profile, state=state, store=store)
python
def set_state(profile, state, store='local'): ''' Configure the firewall state. .. versionadded:: 2018.3.4 .. versionadded:: 2019.2.0 Args: profile (str): The firewall profile to configure. Valid options are: - domain - public - private state (str): The firewall state. Valid options are: - on - off - notconfigured .. note:: ``notconfigured`` can only be used when using the lgpo store store (str): The store to use. This is either the local firewall policy or the policy defined by local group policy. Valid options are: - lgpo - local Default is ``local`` Returns: bool: ``True`` if successful Raises: CommandExecutionError: If an error occurs ValueError: If the parameters are incorrect CLI Example: .. code-block:: bash # Turn the firewall off when the domain profile is active salt * firewall.set_state domain off # Turn the firewall on when the public profile is active and set that in # the local group policy salt * firewall.set_state public on lgpo ''' return salt.utils.win_lgpo_netsh.set_state(profile=profile, state=state, store=store)
[ "def", "set_state", "(", "profile", ",", "state", ",", "store", "=", "'local'", ")", ":", "return", "salt", ".", "utils", ".", "win_lgpo_netsh", ".", "set_state", "(", "profile", "=", "profile", ",", "state", "=", "state", ",", "store", "=", "store", "...
Configure the firewall state. .. versionadded:: 2018.3.4 .. versionadded:: 2019.2.0 Args: profile (str): The firewall profile to configure. Valid options are: - domain - public - private state (str): The firewall state. Valid options are: - on - off - notconfigured .. note:: ``notconfigured`` can only be used when using the lgpo store store (str): The store to use. This is either the local firewall policy or the policy defined by local group policy. Valid options are: - lgpo - local Default is ``local`` Returns: bool: ``True`` if successful Raises: CommandExecutionError: If an error occurs ValueError: If the parameters are incorrect CLI Example: .. code-block:: bash # Turn the firewall off when the domain profile is active salt * firewall.set_state domain off # Turn the firewall on when the public profile is active and set that in # the local group policy salt * firewall.set_state public on lgpo
[ "Configure", "the", "firewall", "state", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_firewall.py#L723-L778
train
saltstack/salt
salt/utils/templates.py
_get_jinja_error
def _get_jinja_error(trace, context=None): ''' Return the error line and error message output from a stacktrace. If we are in a macro, also output inside the message the exact location of the error in the macro ''' if not context: context = {} out = '' error = _get_jinja_error_slug(trace) line = _get_jinja_error_line(trace) msg = _get_jinja_error_message(trace) # if we failed on a nested macro, output a little more info # to help debugging # if sls is not found in context, add output only if we can # resolve the filename add_log = False template_path = None if 'sls' not in context: if ( (error[0] != '<unknown>') and os.path.exists(error[0]) ): template_path = error[0] add_log = True else: # the offender error is not from the called sls filen = context['sls'].replace('.', '/') if ( not error[0].endswith(filen) and os.path.exists(error[0]) ): add_log = True template_path = error[0] # if we add a log, format explicitly the exception here # by telling to output the macro context after the macro # error log place at the beginning if add_log: if template_path: out = '\n{0}\n'.format(msg.splitlines()[0]) with salt.utils.files.fopen(template_path) as fp_: template_contents = salt.utils.stringutils.to_unicode(fp_.read()) out += salt.utils.stringutils.get_context( template_contents, line, marker=' <======================') else: out = '\n{0}\n'.format(msg) line = 0 return line, out
python
def _get_jinja_error(trace, context=None): ''' Return the error line and error message output from a stacktrace. If we are in a macro, also output inside the message the exact location of the error in the macro ''' if not context: context = {} out = '' error = _get_jinja_error_slug(trace) line = _get_jinja_error_line(trace) msg = _get_jinja_error_message(trace) # if we failed on a nested macro, output a little more info # to help debugging # if sls is not found in context, add output only if we can # resolve the filename add_log = False template_path = None if 'sls' not in context: if ( (error[0] != '<unknown>') and os.path.exists(error[0]) ): template_path = error[0] add_log = True else: # the offender error is not from the called sls filen = context['sls'].replace('.', '/') if ( not error[0].endswith(filen) and os.path.exists(error[0]) ): add_log = True template_path = error[0] # if we add a log, format explicitly the exception here # by telling to output the macro context after the macro # error log place at the beginning if add_log: if template_path: out = '\n{0}\n'.format(msg.splitlines()[0]) with salt.utils.files.fopen(template_path) as fp_: template_contents = salt.utils.stringutils.to_unicode(fp_.read()) out += salt.utils.stringutils.get_context( template_contents, line, marker=' <======================') else: out = '\n{0}\n'.format(msg) line = 0 return line, out
[ "def", "_get_jinja_error", "(", "trace", ",", "context", "=", "None", ")", ":", "if", "not", "context", ":", "context", "=", "{", "}", "out", "=", "''", "error", "=", "_get_jinja_error_slug", "(", "trace", ")", "line", "=", "_get_jinja_error_line", "(", ...
Return the error line and error message output from a stacktrace. If we are in a macro, also output inside the message the exact location of the error in the macro
[ "Return", "the", "error", "line", "and", "error", "message", "output", "from", "a", "stacktrace", ".", "If", "we", "are", "in", "a", "macro", "also", "output", "inside", "the", "message", "the", "exact", "location", "of", "the", "error", "in", "the", "ma...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/templates.py#L237-L287
train
saltstack/salt
salt/utils/templates.py
render_genshi_tmpl
def render_genshi_tmpl(tmplstr, context, tmplpath=None): ''' Render a Genshi template. A method should be passed in as part of the context. If no method is passed in, xml is assumed. Valid methods are: .. code-block: - xml - xhtml - html - text - newtext - oldtext Note that the ``text`` method will call ``NewTextTemplate``. If ``oldtext`` is desired, it must be called explicitly ''' method = context.get('method', 'xml') if method == 'text' or method == 'newtext': from genshi.template import NewTextTemplate tmpl = NewTextTemplate(tmplstr) elif method == 'oldtext': from genshi.template import OldTextTemplate tmpl = OldTextTemplate(tmplstr) else: from genshi.template import MarkupTemplate tmpl = MarkupTemplate(tmplstr) return tmpl.generate(**context).render(method)
python
def render_genshi_tmpl(tmplstr, context, tmplpath=None): ''' Render a Genshi template. A method should be passed in as part of the context. If no method is passed in, xml is assumed. Valid methods are: .. code-block: - xml - xhtml - html - text - newtext - oldtext Note that the ``text`` method will call ``NewTextTemplate``. If ``oldtext`` is desired, it must be called explicitly ''' method = context.get('method', 'xml') if method == 'text' or method == 'newtext': from genshi.template import NewTextTemplate tmpl = NewTextTemplate(tmplstr) elif method == 'oldtext': from genshi.template import OldTextTemplate tmpl = OldTextTemplate(tmplstr) else: from genshi.template import MarkupTemplate tmpl = MarkupTemplate(tmplstr) return tmpl.generate(**context).render(method)
[ "def", "render_genshi_tmpl", "(", "tmplstr", ",", "context", ",", "tmplpath", "=", "None", ")", ":", "method", "=", "context", ".", "get", "(", "'method'", ",", "'xml'", ")", "if", "method", "==", "'text'", "or", "method", "==", "'newtext'", ":", "from",...
Render a Genshi template. A method should be passed in as part of the context. If no method is passed in, xml is assumed. Valid methods are: .. code-block: - xml - xhtml - html - text - newtext - oldtext Note that the ``text`` method will call ``NewTextTemplate``. If ``oldtext`` is desired, it must be called explicitly
[ "Render", "a", "Genshi", "template", ".", "A", "method", "should", "be", "passed", "in", "as", "part", "of", "the", "context", ".", "If", "no", "method", "is", "passed", "in", "xml", "is", "assumed", ".", "Valid", "methods", "are", ":" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/templates.py#L485-L513
train
saltstack/salt
salt/utils/templates.py
render_cheetah_tmpl
def render_cheetah_tmpl(tmplstr, context, tmplpath=None): ''' Render a Cheetah template. ''' from Cheetah.Template import Template return salt.utils.data.decode(Template(tmplstr, searchList=[context]))
python
def render_cheetah_tmpl(tmplstr, context, tmplpath=None): ''' Render a Cheetah template. ''' from Cheetah.Template import Template return salt.utils.data.decode(Template(tmplstr, searchList=[context]))
[ "def", "render_cheetah_tmpl", "(", "tmplstr", ",", "context", ",", "tmplpath", "=", "None", ")", ":", "from", "Cheetah", ".", "Template", "import", "Template", "return", "salt", ".", "utils", ".", "data", ".", "decode", "(", "Template", "(", "tmplstr", ","...
Render a Cheetah template.
[ "Render", "a", "Cheetah", "template", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/templates.py#L516-L521
train
saltstack/salt
salt/utils/templates.py
py
def py(sfn, string=False, **kwargs): # pylint: disable=C0103 ''' Render a template from a python source file Returns:: {'result': bool, 'data': <Error data or rendered file path>} ''' if not os.path.isfile(sfn): return {} base_fname = os.path.basename(sfn) name = base_fname.split('.')[0] if USE_IMPORTLIB: # pylint: disable=no-member loader = importlib.machinery.SourceFileLoader(name, sfn) spec = importlib.util.spec_from_file_location(name, sfn, loader=loader) if spec is None: raise ImportError() mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[name] = mod else: mod = imp.load_source(name, sfn) # File templates need these set as __var__ if '__env__' not in kwargs and 'saltenv' in kwargs: setattr(mod, '__env__', kwargs['saltenv']) builtins = ['salt', 'grains', 'pillar', 'opts'] for builtin in builtins: arg = '__{0}__'.format(builtin) setattr(mod, arg, kwargs[builtin]) for kwarg in kwargs: setattr(mod, kwarg, kwargs[kwarg]) try: data = mod.run() if string: return {'result': True, 'data': data} tgt = salt.utils.files.mkstemp() with salt.utils.files.fopen(tgt, 'w+') as target: target.write(salt.utils.stringutils.to_str(data)) return {'result': True, 'data': tgt} except Exception: trb = traceback.format_exc() return {'result': False, 'data': trb}
python
def py(sfn, string=False, **kwargs): # pylint: disable=C0103 ''' Render a template from a python source file Returns:: {'result': bool, 'data': <Error data or rendered file path>} ''' if not os.path.isfile(sfn): return {} base_fname = os.path.basename(sfn) name = base_fname.split('.')[0] if USE_IMPORTLIB: # pylint: disable=no-member loader = importlib.machinery.SourceFileLoader(name, sfn) spec = importlib.util.spec_from_file_location(name, sfn, loader=loader) if spec is None: raise ImportError() mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[name] = mod else: mod = imp.load_source(name, sfn) # File templates need these set as __var__ if '__env__' not in kwargs and 'saltenv' in kwargs: setattr(mod, '__env__', kwargs['saltenv']) builtins = ['salt', 'grains', 'pillar', 'opts'] for builtin in builtins: arg = '__{0}__'.format(builtin) setattr(mod, arg, kwargs[builtin]) for kwarg in kwargs: setattr(mod, kwarg, kwargs[kwarg]) try: data = mod.run() if string: return {'result': True, 'data': data} tgt = salt.utils.files.mkstemp() with salt.utils.files.fopen(tgt, 'w+') as target: target.write(salt.utils.stringutils.to_str(data)) return {'result': True, 'data': tgt} except Exception: trb = traceback.format_exc() return {'result': False, 'data': trb}
[ "def", "py", "(", "sfn", ",", "string", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=C0103", "if", "not", "os", ".", "path", ".", "isfile", "(", "sfn", ")", ":", "return", "{", "}", "base_fname", "=", "os", ".", "path", ".", ...
Render a template from a python source file Returns:: {'result': bool, 'data': <Error data or rendered file path>}
[ "Render", "a", "template", "from", "a", "python", "source", "file" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/templates.py#L525-L577
train
saltstack/salt
salt/modules/namecheap_users.py
get_balances
def get_balances(): ''' Gets information about fund in the user's account. This method returns the following information: Available Balance, Account Balance, Earned Amount, Withdrawable Amount and Funds Required for AutoRenew. .. note:: If a domain setup with automatic renewal is expiring within the next 90 days, the FundsRequiredForAutoRenew attribute shows the amount needed in your Namecheap account to complete auto renewal. CLI Example: .. code-block:: bash salt 'my-minion' namecheap_users.get_balances ''' opts = salt.utils.namecheap.get_opts('namecheap.users.getBalances') response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return {} balance_response = response_xml.getElementsByTagName("UserGetBalancesResult")[0] return salt.utils.namecheap.atts_to_dict(balance_response)
python
def get_balances(): ''' Gets information about fund in the user's account. This method returns the following information: Available Balance, Account Balance, Earned Amount, Withdrawable Amount and Funds Required for AutoRenew. .. note:: If a domain setup with automatic renewal is expiring within the next 90 days, the FundsRequiredForAutoRenew attribute shows the amount needed in your Namecheap account to complete auto renewal. CLI Example: .. code-block:: bash salt 'my-minion' namecheap_users.get_balances ''' opts = salt.utils.namecheap.get_opts('namecheap.users.getBalances') response_xml = salt.utils.namecheap.get_request(opts) if response_xml is None: return {} balance_response = response_xml.getElementsByTagName("UserGetBalancesResult")[0] return salt.utils.namecheap.atts_to_dict(balance_response)
[ "def", "get_balances", "(", ")", ":", "opts", "=", "salt", ".", "utils", ".", "namecheap", ".", "get_opts", "(", "'namecheap.users.getBalances'", ")", "response_xml", "=", "salt", ".", "utils", ".", "namecheap", ".", "get_request", "(", "opts", ")", "if", ...
Gets information about fund in the user's account. This method returns the following information: Available Balance, Account Balance, Earned Amount, Withdrawable Amount and Funds Required for AutoRenew. .. note:: If a domain setup with automatic renewal is expiring within the next 90 days, the FundsRequiredForAutoRenew attribute shows the amount needed in your Namecheap account to complete auto renewal. CLI Example: .. code-block:: bash salt 'my-minion' namecheap_users.get_balances
[ "Gets", "information", "about", "fund", "in", "the", "user", "s", "account", ".", "This", "method", "returns", "the", "following", "information", ":", "Available", "Balance", "Account", "Balance", "Earned", "Amount", "Withdrawable", "Amount", "and", "Funds", "Re...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_users.py#L49-L74
train
saltstack/salt
salt/modules/namecheap_users.py
check_balances
def check_balances(minimum=100): ''' Checks if the provided minimum value is present in the user's account. Returns a boolean. Returns ``False`` if the user's account balance is less than the provided minimum or ``True`` if greater than the minimum. minimum : 100 The value to check CLI Example: .. code-block:: bash salt 'my-minion' namecheap_users.check_balances salt 'my-minion' namecheap_users.check_balances minimum=150 ''' min_float = float(minimum) result = get_balances() if result['accountbalance'] <= min_float: return False return True
python
def check_balances(minimum=100): ''' Checks if the provided minimum value is present in the user's account. Returns a boolean. Returns ``False`` if the user's account balance is less than the provided minimum or ``True`` if greater than the minimum. minimum : 100 The value to check CLI Example: .. code-block:: bash salt 'my-minion' namecheap_users.check_balances salt 'my-minion' namecheap_users.check_balances minimum=150 ''' min_float = float(minimum) result = get_balances() if result['accountbalance'] <= min_float: return False return True
[ "def", "check_balances", "(", "minimum", "=", "100", ")", ":", "min_float", "=", "float", "(", "minimum", ")", "result", "=", "get_balances", "(", ")", "if", "result", "[", "'accountbalance'", "]", "<=", "min_float", ":", "return", "False", "return", "True...
Checks if the provided minimum value is present in the user's account. Returns a boolean. Returns ``False`` if the user's account balance is less than the provided minimum or ``True`` if greater than the minimum. minimum : 100 The value to check CLI Example: .. code-block:: bash salt 'my-minion' namecheap_users.check_balances salt 'my-minion' namecheap_users.check_balances minimum=150
[ "Checks", "if", "the", "provided", "minimum", "value", "is", "present", "in", "the", "user", "s", "account", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/namecheap_users.py#L77-L99
train
saltstack/salt
salt/transport/zeromq.py
_get_master_uri
def _get_master_uri(master_ip, master_port, source_ip=None, source_port=None): ''' Return the ZeroMQ URI to connect the Minion to the Master. It supports different source IP / port, given the ZeroMQ syntax: // Connecting using a IP address and bind to an IP address rc = zmq_connect(socket, "tcp://192.168.1.17:5555;192.168.1.1:5555"); assert (rc == 0); Source: http://api.zeromq.org/4-1:zmq-tcp ''' from salt.utils.zeromq import ip_bracket master_uri = 'tcp://{master_ip}:{master_port}'.format( master_ip=ip_bracket(master_ip), master_port=master_port) if source_ip or source_port: if LIBZMQ_VERSION_INFO >= (4, 1, 6) and ZMQ_VERSION_INFO >= (16, 0, 1): # The source:port syntax for ZeroMQ has been added in libzmq 4.1.6 # which is included in the pyzmq wheels starting with 16.0.1. if source_ip and source_port: master_uri = 'tcp://{source_ip}:{source_port};{master_ip}:{master_port}'.format( source_ip=ip_bracket(source_ip), source_port=source_port, master_ip=ip_bracket(master_ip), master_port=master_port) elif source_ip and not source_port: master_uri = 'tcp://{source_ip}:0;{master_ip}:{master_port}'.format( source_ip=ip_bracket(source_ip), master_ip=ip_bracket(master_ip), master_port=master_port) elif source_port and not source_ip: ip_any = '0.0.0.0' if ipaddress.ip_address(master_ip).version == 4 else ip_bracket('::') master_uri = 'tcp://{ip_any}:{source_port};{master_ip}:{master_port}'.format( ip_any=ip_any, source_port=source_port, master_ip=ip_bracket(master_ip), master_port=master_port) else: log.warning('Unable to connect to the Master using a specific source IP / port') log.warning('Consider upgrading to pyzmq >= 16.0.1 and libzmq >= 4.1.6') log.warning('Specific source IP / port for connecting to master returner port: configuraion ignored') return master_uri
python
def _get_master_uri(master_ip, master_port, source_ip=None, source_port=None): ''' Return the ZeroMQ URI to connect the Minion to the Master. It supports different source IP / port, given the ZeroMQ syntax: // Connecting using a IP address and bind to an IP address rc = zmq_connect(socket, "tcp://192.168.1.17:5555;192.168.1.1:5555"); assert (rc == 0); Source: http://api.zeromq.org/4-1:zmq-tcp ''' from salt.utils.zeromq import ip_bracket master_uri = 'tcp://{master_ip}:{master_port}'.format( master_ip=ip_bracket(master_ip), master_port=master_port) if source_ip or source_port: if LIBZMQ_VERSION_INFO >= (4, 1, 6) and ZMQ_VERSION_INFO >= (16, 0, 1): # The source:port syntax for ZeroMQ has been added in libzmq 4.1.6 # which is included in the pyzmq wheels starting with 16.0.1. if source_ip and source_port: master_uri = 'tcp://{source_ip}:{source_port};{master_ip}:{master_port}'.format( source_ip=ip_bracket(source_ip), source_port=source_port, master_ip=ip_bracket(master_ip), master_port=master_port) elif source_ip and not source_port: master_uri = 'tcp://{source_ip}:0;{master_ip}:{master_port}'.format( source_ip=ip_bracket(source_ip), master_ip=ip_bracket(master_ip), master_port=master_port) elif source_port and not source_ip: ip_any = '0.0.0.0' if ipaddress.ip_address(master_ip).version == 4 else ip_bracket('::') master_uri = 'tcp://{ip_any}:{source_port};{master_ip}:{master_port}'.format( ip_any=ip_any, source_port=source_port, master_ip=ip_bracket(master_ip), master_port=master_port) else: log.warning('Unable to connect to the Master using a specific source IP / port') log.warning('Consider upgrading to pyzmq >= 16.0.1 and libzmq >= 4.1.6') log.warning('Specific source IP / port for connecting to master returner port: configuraion ignored') return master_uri
[ "def", "_get_master_uri", "(", "master_ip", ",", "master_port", ",", "source_ip", "=", "None", ",", "source_port", "=", "None", ")", ":", "from", "salt", ".", "utils", ".", "zeromq", "import", "ip_bracket", "master_uri", "=", "'tcp://{master_ip}:{master_port}'", ...
Return the ZeroMQ URI to connect the Minion to the Master. It supports different source IP / port, given the ZeroMQ syntax: // Connecting using a IP address and bind to an IP address rc = zmq_connect(socket, "tcp://192.168.1.17:5555;192.168.1.1:5555"); assert (rc == 0); Source: http://api.zeromq.org/4-1:zmq-tcp
[ "Return", "the", "ZeroMQ", "URI", "to", "connect", "the", "Minion", "to", "the", "Master", ".", "It", "supports", "different", "source", "IP", "/", "port", "given", "the", "ZeroMQ", "syntax", ":", "//", "Connecting", "using", "a", "IP", "address", "and", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/zeromq.py#L70-L108
train
saltstack/salt
salt/transport/zeromq.py
_set_tcp_keepalive
def _set_tcp_keepalive(zmq_socket, opts): ''' Ensure that TCP keepalives are set as specified in "opts". Warning: Failure to set TCP keepalives on the salt-master can result in not detecting the loss of a minion when the connection is lost or when it's host has been terminated without first closing the socket. Salt's Presence System depends on this connection status to know if a minion is "present". Warning: Failure to set TCP keepalives on minions can result in frequent or unexpected disconnects! ''' if hasattr(zmq, 'TCP_KEEPALIVE') and opts: if 'tcp_keepalive' in opts: zmq_socket.setsockopt( zmq.TCP_KEEPALIVE, opts['tcp_keepalive'] ) if 'tcp_keepalive_idle' in opts: zmq_socket.setsockopt( zmq.TCP_KEEPALIVE_IDLE, opts['tcp_keepalive_idle'] ) if 'tcp_keepalive_cnt' in opts: zmq_socket.setsockopt( zmq.TCP_KEEPALIVE_CNT, opts['tcp_keepalive_cnt'] ) if 'tcp_keepalive_intvl' in opts: zmq_socket.setsockopt( zmq.TCP_KEEPALIVE_INTVL, opts['tcp_keepalive_intvl'] )
python
def _set_tcp_keepalive(zmq_socket, opts): ''' Ensure that TCP keepalives are set as specified in "opts". Warning: Failure to set TCP keepalives on the salt-master can result in not detecting the loss of a minion when the connection is lost or when it's host has been terminated without first closing the socket. Salt's Presence System depends on this connection status to know if a minion is "present". Warning: Failure to set TCP keepalives on minions can result in frequent or unexpected disconnects! ''' if hasattr(zmq, 'TCP_KEEPALIVE') and opts: if 'tcp_keepalive' in opts: zmq_socket.setsockopt( zmq.TCP_KEEPALIVE, opts['tcp_keepalive'] ) if 'tcp_keepalive_idle' in opts: zmq_socket.setsockopt( zmq.TCP_KEEPALIVE_IDLE, opts['tcp_keepalive_idle'] ) if 'tcp_keepalive_cnt' in opts: zmq_socket.setsockopt( zmq.TCP_KEEPALIVE_CNT, opts['tcp_keepalive_cnt'] ) if 'tcp_keepalive_intvl' in opts: zmq_socket.setsockopt( zmq.TCP_KEEPALIVE_INTVL, opts['tcp_keepalive_intvl'] )
[ "def", "_set_tcp_keepalive", "(", "zmq_socket", ",", "opts", ")", ":", "if", "hasattr", "(", "zmq", ",", "'TCP_KEEPALIVE'", ")", "and", "opts", ":", "if", "'tcp_keepalive'", "in", "opts", ":", "zmq_socket", ".", "setsockopt", "(", "zmq", ".", "TCP_KEEPALIVE"...
Ensure that TCP keepalives are set as specified in "opts". Warning: Failure to set TCP keepalives on the salt-master can result in not detecting the loss of a minion when the connection is lost or when it's host has been terminated without first closing the socket. Salt's Presence System depends on this connection status to know if a minion is "present". Warning: Failure to set TCP keepalives on minions can result in frequent or unexpected disconnects!
[ "Ensure", "that", "TCP", "keepalives", "are", "set", "as", "specified", "in", "opts", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/zeromq.py#L800-L829
train
saltstack/salt
salt/transport/zeromq.py
AsyncZeroMQReqChannel._uncrypted_transfer
def _uncrypted_transfer(self, load, tries=3, timeout=60): ''' Send a load across the wire in cleartext :param dict load: A load to send across the wire :param int tries: The number of times to make before failure :param int timeout: The number of seconds on a response before failing ''' ret = yield self.message_client.send( self._package_load(load), timeout=timeout, tries=tries, ) raise tornado.gen.Return(ret)
python
def _uncrypted_transfer(self, load, tries=3, timeout=60): ''' Send a load across the wire in cleartext :param dict load: A load to send across the wire :param int tries: The number of times to make before failure :param int timeout: The number of seconds on a response before failing ''' ret = yield self.message_client.send( self._package_load(load), timeout=timeout, tries=tries, ) raise tornado.gen.Return(ret)
[ "def", "_uncrypted_transfer", "(", "self", ",", "load", ",", "tries", "=", "3", ",", "timeout", "=", "60", ")", ":", "ret", "=", "yield", "self", ".", "message_client", ".", "send", "(", "self", ".", "_package_load", "(", "load", ")", ",", "timeout", ...
Send a load across the wire in cleartext :param dict load: A load to send across the wire :param int tries: The number of times to make before failure :param int timeout: The number of seconds on a response before failing
[ "Send", "a", "load", "across", "the", "wire", "in", "cleartext" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/zeromq.py#L353-L367
train
saltstack/salt
salt/transport/zeromq.py
AsyncZeroMQReqChannel.send
def send(self, load, tries=3, timeout=60, raw=False): ''' Send a request, return a future which will complete when we send the message ''' if self.crypt == 'clear': ret = yield self._uncrypted_transfer(load, tries=tries, timeout=timeout) else: ret = yield self._crypted_transfer(load, tries=tries, timeout=timeout, raw=raw) raise tornado.gen.Return(ret)
python
def send(self, load, tries=3, timeout=60, raw=False): ''' Send a request, return a future which will complete when we send the message ''' if self.crypt == 'clear': ret = yield self._uncrypted_transfer(load, tries=tries, timeout=timeout) else: ret = yield self._crypted_transfer(load, tries=tries, timeout=timeout, raw=raw) raise tornado.gen.Return(ret)
[ "def", "send", "(", "self", ",", "load", ",", "tries", "=", "3", ",", "timeout", "=", "60", ",", "raw", "=", "False", ")", ":", "if", "self", ".", "crypt", "==", "'clear'", ":", "ret", "=", "yield", "self", ".", "_uncrypted_transfer", "(", "load", ...
Send a request, return a future which will complete when we send the message
[ "Send", "a", "request", "return", "a", "future", "which", "will", "complete", "when", "we", "send", "the", "message" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/zeromq.py#L370-L378
train
saltstack/salt
salt/transport/zeromq.py
AsyncZeroMQPubChannel.master_pub
def master_pub(self): ''' Return the master publish port ''' return _get_master_uri(self.opts['master_ip'], self.publish_port, source_ip=self.opts.get('source_ip'), source_port=self.opts.get('source_publish_port'))
python
def master_pub(self): ''' Return the master publish port ''' return _get_master_uri(self.opts['master_ip'], self.publish_port, source_ip=self.opts.get('source_ip'), source_port=self.opts.get('source_publish_port'))
[ "def", "master_pub", "(", "self", ")", ":", "return", "_get_master_uri", "(", "self", ".", "opts", "[", "'master_ip'", "]", ",", "self", ".", "publish_port", ",", "source_ip", "=", "self", ".", "opts", ".", "get", "(", "'source_ip'", ")", ",", "source_po...
Return the master publish port
[ "Return", "the", "master", "publish", "port" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/zeromq.py#L514-L521
train
saltstack/salt
salt/transport/zeromq.py
AsyncZeroMQPubChannel._decode_messages
def _decode_messages(self, messages): ''' Take the zmq messages, decrypt/decode them into a payload :param list messages: A list of messages to be decoded ''' messages_len = len(messages) # if it was one message, then its old style if messages_len == 1: payload = self.serial.loads(messages[0]) # 2 includes a header which says who should do it elif messages_len == 2: if (self.opts.get('__role') != 'syndic' and messages[0] not in ('broadcast', self.hexid)) or \ (self.opts.get('__role') == 'syndic' and messages[0] not in ('broadcast', 'syndic')): log.debug('Publish received for not this minion: %s', messages[0]) raise tornado.gen.Return(None) payload = self.serial.loads(messages[1]) else: raise Exception(('Invalid number of messages ({0}) in zeromq pub' 'message from master').format(len(messages_len))) # Yield control back to the caller. When the payload has been decoded, assign # the decoded payload to 'ret' and resume operation ret = yield self._decode_payload(payload) raise tornado.gen.Return(ret)
python
def _decode_messages(self, messages): ''' Take the zmq messages, decrypt/decode them into a payload :param list messages: A list of messages to be decoded ''' messages_len = len(messages) # if it was one message, then its old style if messages_len == 1: payload = self.serial.loads(messages[0]) # 2 includes a header which says who should do it elif messages_len == 2: if (self.opts.get('__role') != 'syndic' and messages[0] not in ('broadcast', self.hexid)) or \ (self.opts.get('__role') == 'syndic' and messages[0] not in ('broadcast', 'syndic')): log.debug('Publish received for not this minion: %s', messages[0]) raise tornado.gen.Return(None) payload = self.serial.loads(messages[1]) else: raise Exception(('Invalid number of messages ({0}) in zeromq pub' 'message from master').format(len(messages_len))) # Yield control back to the caller. When the payload has been decoded, assign # the decoded payload to 'ret' and resume operation ret = yield self._decode_payload(payload) raise tornado.gen.Return(ret)
[ "def", "_decode_messages", "(", "self", ",", "messages", ")", ":", "messages_len", "=", "len", "(", "messages", ")", "# if it was one message, then its old style", "if", "messages_len", "==", "1", ":", "payload", "=", "self", ".", "serial", ".", "loads", "(", ...
Take the zmq messages, decrypt/decode them into a payload :param list messages: A list of messages to be decoded
[ "Take", "the", "zmq", "messages", "decrypt", "/", "decode", "them", "into", "a", "payload" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/zeromq.py#L524-L547
train
saltstack/salt
salt/transport/zeromq.py
AsyncZeroMQPubChannel.stream
def stream(self): ''' Return the current zmqstream, creating one if necessary ''' if not hasattr(self, '_stream'): self._stream = zmq.eventloop.zmqstream.ZMQStream(self._socket, io_loop=self.io_loop) return self._stream
python
def stream(self): ''' Return the current zmqstream, creating one if necessary ''' if not hasattr(self, '_stream'): self._stream = zmq.eventloop.zmqstream.ZMQStream(self._socket, io_loop=self.io_loop) return self._stream
[ "def", "stream", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_stream'", ")", ":", "self", ".", "_stream", "=", "zmq", ".", "eventloop", ".", "zmqstream", ".", "ZMQStream", "(", "self", ".", "_socket", ",", "io_loop", "=", "self...
Return the current zmqstream, creating one if necessary
[ "Return", "the", "current", "zmqstream", "creating", "one", "if", "necessary" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/zeromq.py#L550-L556
train
saltstack/salt
salt/transport/zeromq.py
AsyncZeroMQPubChannel.on_recv
def on_recv(self, callback): ''' Register a callback for received messages (that we didn't initiate) :param func callback: A function which should be called when data is received ''' if callback is None: return self.stream.on_recv(None) @tornado.gen.coroutine def wrap_callback(messages): payload = yield self._decode_messages(messages) if payload is not None: callback(payload) return self.stream.on_recv(wrap_callback)
python
def on_recv(self, callback): ''' Register a callback for received messages (that we didn't initiate) :param func callback: A function which should be called when data is received ''' if callback is None: return self.stream.on_recv(None) @tornado.gen.coroutine def wrap_callback(messages): payload = yield self._decode_messages(messages) if payload is not None: callback(payload) return self.stream.on_recv(wrap_callback)
[ "def", "on_recv", "(", "self", ",", "callback", ")", ":", "if", "callback", "is", "None", ":", "return", "self", ".", "stream", ".", "on_recv", "(", "None", ")", "@", "tornado", ".", "gen", ".", "coroutine", "def", "wrap_callback", "(", "messages", ")"...
Register a callback for received messages (that we didn't initiate) :param func callback: A function which should be called when data is received
[ "Register", "a", "callback", "for", "received", "messages", "(", "that", "we", "didn", "t", "initiate", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/transport/zeromq.py#L558-L572
train