Sodium deprecations (#57370)

* Drop deprecated mac_brew_pkg namespace fixup

Closes #57361

* Note deprecation in release notes

* Remove deprecated napalm_network features

Closes #57362

These arguments are no longer useful, since we no longer support using
NAPALM native templates.

* Remove selinux.fcontext_add_or_delete_policy

It was deprecated and slated for removal in Sodium. Closes #57363

* Remove deprecated refresh_db param

Closes #57366

Parameter has been renamed to `refresh`

* Remove deprecated sdecode functions

Closes #57367

sdecode and sdecode_if_string functionalities have both been moved to
decode.

* Remove assorted deprecated features

Closes #57368

- removed obsolete .destroy methods from zeromq channels
- removed winexe support from salt.utils.cloud
- removed obsolete override_name from
  salt.utils.context.NamespacedDictWrapper
- removed obsolete `show_ipv4` parameter from salt.utils.minions
- removed impacket support from salt.utils.smb
- removed obsolete salt.transport.Channel, and fixed test.

* Change module.run deprecation version

* Remove deprecated destroy test

* Remove deprecation from skip

* Re-add keystone docs

* Blacken merge conflict

Co-authored-by: Daniel Wozniak <dwozniak@saltstack.com>
This commit is contained in:
Wayne Werner 2020-05-21 21:46:14 -05:00 committed by GitHub
parent 2eb7c9051d
commit ee181c97a5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
21 changed files with 123 additions and 525 deletions

1
changelog/57361.removed Normal file
View file

@ -0,0 +1 @@
On macOS pkg.installed (using brew) no longer swaps `caskroom/cask/` for `homebrew/cask/` when using outdated package names.

3
changelog/57362.removed Normal file
View file

@ -0,0 +1,3 @@
napalm_network.load_template module - removed deprecated arguments
template_user, template_attrs, template_group, template_mode, and native NAPALM
template support. Use Salt's rendering pipeline instead.

1
changelog/57363.removed Normal file
View file

@ -0,0 +1 @@
selinux.fcontext_add_or_delete_policy module removed - use selinux.fcontext_add_policy or selinux.fcontext_delete_pollicy instead.

1
changelog/57366.removed Normal file
View file

@ -0,0 +1 @@
Deprecated `refresh_db` removed from pkgrepo state. Use `refresh` instead.

1
changelog/57367.removed Normal file
View file

@ -0,0 +1 @@
Deprecated internal functions salt.utils.locales.sdecode and .sdecode_if_string removed. Use salt.utils.data.decode instead.

1
changelog/57368.removed Normal file
View file

@ -0,0 +1 @@
Removed deprecated misc. internal Salt functions. See https://github.com/saltstack/salt/issues/57368 for more info.

View file

@ -4,6 +4,13 @@
Salt Release Notes - Codename Sodium
====================================
Python 2 Deprecation
====================
Python 2 support has been dropped in Salt 3001. See
https://community.saltstack.com/blog/sunsetting-python-2-support/ for more
info.
Salt mine updates
=================

View file

@ -304,7 +304,6 @@ def remove(name=None, pkgs=None, **kwargs):
salt '*' pkg.remove pkgs='["foo", "bar"]'
"""
try:
name, pkgs = _fix_cask_namespace(name, pkgs)
pkg_params = __salt__["pkg_resource.parse_targets"](name, pkgs, **kwargs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
@ -441,7 +440,6 @@ def install(name=None, pkgs=None, taps=None, options=None, **kwargs):
salt '*' pkg.install 'package package package'
"""
try:
name, pkgs = _fix_cask_namespace(name, pkgs)
pkg_params, pkg_type = __salt__["pkg_resource.parse_targets"](
name, pkgs, kwargs.get("sources", {})
)

View file

@ -1941,22 +1941,6 @@ def load_template(
_loaded = {"result": True, "comment": "", "out": None}
loaded_config = None
# prechecks
deprecated_args = (
"template_user",
"template_attrs",
"template_group",
"template_mode",
)
for deprecated_arg in deprecated_args:
if template_vars.get(deprecated_arg):
del template_vars[deprecated_arg]
salt.utils.versions.warn_until(
"Sodium",
(
"The '{arg}' argument to 'net.load_template' is deprecated "
"and has been ignored"
).format(arg=deprecated_arg),
)
if template_engine not in salt.utils.templates.TEMPLATE_REGISTRY:
_loaded.update(
{
@ -1982,158 +1966,112 @@ def load_template(
)
file_exists = __salt__["file.file_exists"](template_name)
if (
template_source
or file_exists
or salt_render
or isinstance(template_name, (tuple, list))
):
# either inline template
# either template in a custom path
# either abs path send
# either starts with salt:// and
# then use Salt render system
if context is None:
context = {}
context.update(template_vars)
# if needed to render the template send as inline arg
if template_source:
# render the content
_rendered = __salt__["file.apply_template_on_contents"](
contents=template_source,
if context is None:
context = {}
context.update(template_vars)
# if needed to render the template send as inline arg
if template_source:
# render the content
_rendered = __salt__["file.apply_template_on_contents"](
contents=template_source,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
)
if not isinstance(_rendered, six.string_types):
if "result" in _rendered:
_loaded["result"] = _rendered["result"]
else:
_loaded["result"] = False
if "comment" in _rendered:
_loaded["comment"] = _rendered["comment"]
else:
_loaded["comment"] = "Error while rendering the template."
return _loaded
else:
# render the file - either local, either remote
if not isinstance(template_name, (list, tuple)):
template_name = [template_name]
if template_hash_name and not isinstance(template_hash_name, (list, tuple)):
template_hash_name = [template_hash_name]
elif not template_hash_name:
template_hash_name = [None] * len(template_name)
if (
template_hash
and isinstance(template_hash, six.string_types)
and not (
template_hash.startswith("salt://")
or template_hash.startswith("file://")
)
):
# If the template hash is passed as string, and it's not a file
# (starts with the salt:// or file:// URI), then make it a list
# of 1 element (for the iteration below)
template_hash = [template_hash]
elif (
template_hash
and isinstance(template_hash, six.string_types)
and (
template_hash.startswith("salt://")
or template_hash.startswith("file://")
)
):
# If the template hash is a file URI, then provide the same value
# for each of the templates in the list, as probably they all
# share the same hash file, otherwise the user should provide
# this as a list
template_hash = [template_hash] * len(template_name)
elif not template_hash:
template_hash = [None] * len(template_name)
for tpl_index, tpl_name in enumerate(template_name):
tpl_hash = template_hash[tpl_index]
tpl_hash_name = template_hash_name[tpl_index]
_rand_filename = __salt__["random.hash"](tpl_name, "md5")
_temp_file = __salt__["file.join"]("/tmp", _rand_filename)
_managed = __salt__["file.get_managed"](
name=_temp_file,
source=tpl_name,
source_hash=tpl_hash,
source_hash_name=tpl_hash_name,
user=None,
group=None,
mode=None,
attrs=None,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
skip_verify=skip_verify,
)
if not isinstance(_rendered, six.string_types):
if "result" in _rendered:
_loaded["result"] = _rendered["result"]
else:
_loaded["result"] = False
if "comment" in _rendered:
_loaded["comment"] = _rendered["comment"]
else:
_loaded["comment"] = "Error while rendering the template."
return _loaded
else:
# render the file - either local, either remote
if not isinstance(template_name, (list, tuple)):
template_name = [template_name]
if template_hash_name and not isinstance(template_hash_name, (list, tuple)):
template_hash_name = [template_hash_name]
elif not template_hash_name:
template_hash_name = [None] * len(template_name)
if (
template_hash
and isinstance(template_hash, six.string_types)
and not (
template_hash.startswith("salt://")
or template_hash.startswith("file://")
)
if not isinstance(_managed, (list, tuple)) and isinstance(
_managed, six.string_types
):
# If the template hash is passed as string, and it's not a file
# (starts with the salt:// or file:// URI), then make it a list
# of 1 element (for the iteration below)
template_hash = [template_hash]
elif (
template_hash
and isinstance(template_hash, six.string_types)
and (
template_hash.startswith("salt://")
or template_hash.startswith("file://")
)
):
# If the template hash is a file URI, then provide the same value
# for each of the templates in the list, as probably they all
# share the same hash file, otherwise the user should provide
# this as a list
template_hash = [template_hash] * len(template_name)
elif not template_hash:
template_hash = [None] * len(template_name)
for tpl_index, tpl_name in enumerate(template_name):
tpl_hash = template_hash[tpl_index]
tpl_hash_name = template_hash_name[tpl_index]
_rand_filename = __salt__["random.hash"](tpl_name, "md5")
_temp_file = __salt__["file.join"]("/tmp", _rand_filename)
_managed = __salt__["file.get_managed"](
name=_temp_file,
source=tpl_name,
source_hash=tpl_hash,
source_hash_name=tpl_hash_name,
user=None,
group=None,
mode=None,
attrs=None,
template=template_engine,
context=context,
defaults=defaults,
saltenv=saltenv,
skip_verify=skip_verify,
)
if not isinstance(_managed, (list, tuple)) and isinstance(
_managed, six.string_types
):
_loaded["comment"] += _managed
_loaded["result"] = False
elif isinstance(_managed, (list, tuple)) and not len(_managed) > 0:
_loaded["comment"] += _managed
_loaded["result"] = False
elif isinstance(_managed, (list, tuple)) and not len(_managed) > 0:
_loaded["result"] = False
_loaded["comment"] += "Error while rendering the template."
elif isinstance(_managed, (list, tuple)) and not len(_managed[0]) > 0:
_loaded["result"] = False
_loaded["comment"] += _managed[-1] # contains the error message
if _loaded["result"]: # all good
_temp_tpl_file = _managed[0]
_temp_tpl_file_exists = __salt__["file.file_exists"](_temp_tpl_file)
if not _temp_tpl_file_exists:
_loaded["result"] = False
_loaded["comment"] += "Error while rendering the template."
elif isinstance(_managed, (list, tuple)) and not len(_managed[0]) > 0:
_loaded["result"] = False
_loaded["comment"] += _managed[-1] # contains the error message
if _loaded["result"]: # all good
_temp_tpl_file = _managed[0]
_temp_tpl_file_exists = __salt__["file.file_exists"](_temp_tpl_file)
if not _temp_tpl_file_exists:
_loaded["result"] = False
_loaded["comment"] += "Error while rendering the template."
return _loaded
_rendered += __salt__["file.read"](_temp_tpl_file)
__salt__["file.remove"](_temp_tpl_file)
else:
return _loaded # exit
return _loaded
_rendered += __salt__["file.read"](_temp_tpl_file)
__salt__["file.remove"](_temp_tpl_file)
else:
return _loaded # exit
loaded_config = _rendered
if _loaded["result"]: # all good
fun = "load_merge_candidate"
if replace: # replace requested
fun = "load_replace_candidate"
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
# do not close the connection after loading the config
# this will be handled in _config_logic
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
napalm_device["CLOSE"] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
fun,
**{"config": _rendered}
)
else:
salt.utils.versions.warn_until(
"Sodium",
"Native NAPALM templates support will be removed in the Sodium "
"release. Please consider using the Salt rendering pipeline instead."
"If you are using the 'netntp', 'netsnmp', or 'netusers' Salt "
"State modules, you can ignore this message",
)
# otherwise, use NAPALM render system, injecting pillar/grains/opts vars
load_templates_params = defaults if defaults else {}
load_templates_params.update(template_vars)
load_templates_params.update(
{
"template_name": template_name,
"template_source": template_source, # inline template
"pillar": __pillar__, # inject pillar content
"grains": __grains__, # inject grains content
"opts": __opts__, # inject opts content
}
)
loaded_config = _rendered
if _loaded["result"]: # all good
fun = "load_merge_candidate"
if replace: # replace requested
fun = "load_replace_candidate"
if salt.utils.napalm.not_always_alive(__opts__):
# if a not-always-alive proxy
# or regular minion
@ -2142,12 +2080,11 @@ def load_template(
# after running the other features:
# compare_config, discard / commit
# which have to be over the same session
# so we'll set the CLOSE global explicitly as False
napalm_device["CLOSE"] = False # pylint: disable=undefined-variable
_loaded = salt.utils.napalm.call(
napalm_device, # pylint: disable=undefined-variable
"load_template",
**load_templates_params
fun,
**{"config": _rendered}
)
return _config_logic(
napalm_device, # pylint: disable=undefined-variable

View file

@ -606,66 +606,6 @@ def fcontext_delete_policy(
)
def fcontext_add_or_delete_policy(
action, name, filetype=None, sel_type=None, sel_user=None, sel_level=None
):
"""
.. versionadded:: 2017.7.0
Adds or deletes the SELinux policy for a given filespec and other optional parameters.
Returns the result of the call to semanage.
Note that you don't have to remove an entry before setting a new
one for a given filespec and filetype, as adding one with semanage
automatically overwrites a previously configured SELinux context.
.. warning::
Use :mod:`selinux.fcontext_add_policy()<salt.modules.selinux.fcontext_add_policy>`,
or :mod:`selinux.fcontext_delete_policy()<salt.modules.selinux.fcontext_delete_policy>`.
.. deprecated:: 2019.2.0
action
The action to perform. Either ``add`` or ``delete``.
name
filespec of the file or directory. Regex syntax is allowed.
file_type
The SELinux filetype specification. Use one of [a, f, d, c, b,
s, l, p]. See also ``man semanage-fcontext``. Defaults to 'a'
(all files).
sel_type
SELinux context type. There are many.
sel_user
SELinux user. Use ``semanage login -l`` to determine which ones
are available to you.
sel_level
The MLS range of the SELinux context.
CLI Example:
.. code-block:: bash
salt '*' selinux.fcontext_add_or_delete_policy add my-policy
"""
salt.utils.versions.warn_until(
"Sodium",
"The 'selinux.fcontext_add_or_delete_policy' module has been deprecated. Please use the "
"'selinux.fcontext_add_policy' and 'selinux.fcontext_delete_policy' modules instead. "
"Support for the 'selinux.fcontext_add_or_delete_policy' module will be removed in Salt "
"{version}.",
)
return _fcontext_add_or_delete_policy(
action, name, filetype, sel_type, sel_user, sel_level
)
def _fcontext_add_or_delete_policy(
action, name, filetype=None, sel_type=None, sel_user=None, sel_level=None
):

View file

@ -342,7 +342,7 @@ def wait(name, **kwargs):
watch = salt.utils.functools.alias_function(wait, "watch")
@with_deprecated(globals(), "Sodium", policy=with_deprecated.OPT_IN)
@with_deprecated(globals(), "Phosphorus", policy=with_deprecated.OPT_IN)
def run(**kwargs):
"""
Run a single module function or a range of module functions in a batch.

View file

@ -309,14 +309,6 @@ def managed(name, ppa=None, **kwargs):
running of apt-get update prior to attempting to install these
packages. Setting a require in the pkg state will not work for this.
"""
if "refresh_db" in kwargs:
salt.utils.versions.warn_until(
"Sodium",
"The 'refresh_db' argument to 'pkg.mod_repo' has been "
"renamed to 'refresh'. Support for using 'refresh_db' will be "
"removed in the Sodium release of Salt.",
)
kwargs["refresh"] = kwargs.pop("refresh_db")
ret = {"name": name, "changes": {}, "result": None, "comment": ""}

View file

@ -34,20 +34,6 @@ def iter_transport_opts(opts):
yield opts["transport"], opts
# for backwards compatibility
class Channel(object):
@staticmethod
def factory(opts, **kwargs):
salt.utils.versions.warn_until(
"Sodium",
"Stop using salt.transport.Channel and instead use salt.transport.client.ReqChannel",
stacklevel=3,
)
from salt.transport.client import ReqChannel
return ReqChannel.factory(opts, **kwargs)
class MessageClientPool(object):
def __init__(self, tgt, opts, args=None, kwargs=None):
sock_pool_size = opts["sock_pool_size"] if "sock_pool_size" in opts else 1

View file

@ -558,17 +558,6 @@ class AsyncZeroMQPubChannel(
if hasattr(self, "context") and self.context.closed is False:
self.context.term()
def destroy(self):
# Bacwards compat
salt.utils.versions.warn_until(
"Sodium",
"Calling {0}.destroy() is deprecated. Please call {0}.close() instead.".format(
self.__class__.__name__
),
stacklevel=3,
)
self.close()
# pylint: disable=W1701
def __del__(self):
self.close()
@ -1191,17 +1180,6 @@ class AsyncReqMessageClientPool(salt.transport.MessageClientPool):
message_clients = sorted(self.message_clients, key=lambda x: len(x.send_queue))
return message_clients[0].send(*args, **kwargs)
def destroy(self):
# Bacwards compat
salt.utils.versions.warn_until(
"Sodium",
"Calling {0}.destroy() is deprecated. Please call {0}.close() instead.".format(
self.__class__.__name__
),
stacklevel=3,
)
self.close()
# pylint: disable=W1701
def __del__(self):
self.close()
@ -1277,17 +1255,6 @@ class AsyncReqMessageClient(object):
if self.context.closed is False:
self.context.term()
def destroy(self):
# Bacwards compat
salt.utils.versions.warn_until(
"Sodium",
"Calling {0}.destroy() is deprecated. Please call {0}.close() instead.".format(
self.__class__.__name__
),
stacklevel=3,
)
self.close()
# pylint: disable=W1701
def __del__(self):
self.close()

View file

@ -207,13 +207,6 @@ def __ssh_gateway_arguments(kwargs):
return extended_arguments
def has_winexe():
"""
True when winexe is found on the system
"""
return salt.utils.path.which("winexe")
def os_script(os_, vm_=None, opts=None, minion=""):
"""
Return the script as a string for the specific os
@ -959,9 +952,6 @@ def run_psexec_command(cmd, args, host, username, password, port=445):
"""
Run a command remotly using the psexec protocol
"""
if has_winexe() and not HAS_PSEXEC:
ret_code = run_winexe_command(cmd, args, host, username, password, port)
return None, None, ret_code
service_name = "PS-Exec-{0}".format(uuid.uuid4())
stdout, stderr, ret_code = "", "", None
client = Client(
@ -1007,8 +997,6 @@ def wait_for_psexecsvc(host, port, username, password, timeout=900):
"""
Wait until psexec connection can be established.
"""
if has_winexe() and not HAS_PSEXEC:
return wait_for_winexe(host, port, username, password, timeout)
start = time.time()
try_count = 0
while True:
@ -1234,13 +1222,6 @@ def deploy_windows(
log.error("WinRM requested but module winrm could not be imported")
return False
if not use_winrm and has_winexe() and not HAS_PSEXEC:
salt.utils.versions.warn_until(
"Sodium",
"Support for winexe has been deprecated and will be removed in "
"Sodium, please install pypsexec instead.",
)
starttime = time.mktime(time.localtime())
log.debug("Deploying %s at %s (Windows)", host, starttime)
log.trace("HAS_WINRM: %s, use_winrm: %s", HAS_WINRM, use_winrm)

View file

@ -200,21 +200,12 @@ class NamespacedDictWrapper(MutableMapping, dict):
MUST inherit from dict to serialize through msgpack correctly
"""
def __init__(self, d, pre_keys, override_name=None): # pylint: disable=W0231
def __init__(self, d, pre_keys): # pylint: disable=W0231
self.__dict = d
if isinstance(pre_keys, six.string_types):
self.pre_keys = (pre_keys,)
else:
self.pre_keys = pre_keys
if override_name is not None:
import salt.utils.versions
salt.utils.versions.warn_until(
"Sodium",
"Overriding the class name is no longer supported. Please "
"remove the override_name argument before it is removed in "
"Salt Sodium.",
)
super(NamespacedDictWrapper, self).__init__(self._dict())
def _dict(self):

View file

@ -3,13 +3,10 @@
the locale utils used by salt
"""
# Import Python libs
from __future__ import absolute_import, unicode_literals
import sys
# Import Salt libs
import salt.utils.versions
from salt.utils.decorators import memoize as real_memoize
@ -34,28 +31,6 @@ def get_encodings():
return encodings
def sdecode(string_):
salt.utils.versions.warn_until(
"Sodium",
"Use of 'salt.utils.locales.sdecode' detected. This function "
"has been replaced by 'salt.utils.data.decode' as of "
"Salt 2019.2.0. This warning will be removed in Salt Sodium.",
stacklevel=3,
)
return salt.utils.data.decode(string_)
def sdecode_if_string(value_):
salt.utils.versions.warn_until(
"Sodium",
"Use of 'salt.utils.locales.sdecode_if_string' detected. This "
"function has been replaced by 'salt.utils.data.decode' as of "
"Salt 2019.2.0. This warning will be removed in Salt Sodium.",
stacklevel=3,
)
return salt.utils.data.decode(value_)
def split_locale(loc):
"""
Split a locale specifier. The general format is

View file

@ -639,9 +639,7 @@ class CkMinions(object):
return {"minions": list(minions), "missing": []}
def connected_ids(
self, subset=None, show_ip=False, show_ipv4=None, include_localhost=None
):
def connected_ids(self, subset=None, show_ip=False, include_localhost=None):
"""
Return a set of all connected minion ids, optionally within a subset
"""
@ -651,13 +649,6 @@ class CkMinions(object):
"The 'include_localhost' argument is no longer required; any"
"connected localhost minion will always be included.",
)
if show_ipv4 is not None:
salt.utils.versions.warn_until(
"Sodium",
"The 'show_ipv4' argument has been renamed to 'show_ip' as"
"it now also includes IPv6 addresses for IPv6-connected"
"minions.",
)
minions = set()
if self.opts.get("minion_data_cache", False):
search = self.cache.list("minions")

View file

@ -20,15 +20,6 @@ from salt.exceptions import MissingSmb
log = logging.getLogger(__name__)
try:
import impacket.smbconnection
from impacket.smbconnection import SessionError as smbSessionError
from impacket.smb3 import SessionError as smb3SessionError
HAS_IMPACKET = True
except ImportError:
HAS_IMPACKET = False
try:
from smbprotocol.connection import Connection
from smbprotocol.session import Session
@ -148,39 +139,6 @@ class SMBProto(object):
return dir_open
class StrHandle(object):
"""
Fakes a file handle, so that raw strings may be uploaded instead of having
to write files first. Used by put_str()
"""
def __init__(self, content):
"""
Init
"""
self.content = content
self.finished = False
def string(self, writesize=None):
"""
Looks like a file handle
"""
if not self.finished:
self.finished = True
return self.content
return ""
def _get_conn_impacket(
host=None, username=None, password=None, client_name=None, port=445
):
conn = impacket.smbconnection.SMBConnection(
remoteName=host, remoteHost=host, myName=client_name,
)
conn.login(user=username, password=password)
return conn
def _get_conn_smbprotocol(host="", username="", password="", client_name="", port=445):
conn = SMBProto(host, username, password, port)
conn.connect()
@ -191,47 +149,12 @@ def get_conn(host="", username=None, password=None, port=445):
"""
Get an SMB connection
"""
if HAS_IMPACKET and not HAS_SMBPROTOCOL:
salt.utils.versions.warn_until(
"Sodium",
"Support of impacket has been depricated and will be "
"removed in Sodium. Please install smbprotocol instead.",
)
if HAS_SMBPROTOCOL:
log.info("Get connection smbprotocol")
return _get_conn_smbprotocol(host, username, password, port=port)
elif HAS_IMPACKET:
log.info("Get connection impacket")
return _get_conn_impacket(host, username, password, port=port)
return False
def _mkdirs_impacket(
path, share="C$", conn=None, host=None, username=None, password=None
):
"""
Recursively create a directory structure on an SMB share
Paths should be passed in with forward-slash delimiters, and should not
start with a forward-slash.
"""
if conn is None:
conn = get_conn(host, username, password)
if conn is False:
else:
return False
comps = path.split("/")
pos = 1
for comp in comps:
cwd = "\\".join(comps[0:pos])
try:
conn.listPath(share, cwd)
except (smbSessionError, smb3SessionError):
log.exception("Encountered error running conn.listPath")
conn.createDirectory(share, cwd)
pos += 1
def _mkdirs_smbprotocol(
path, share="C$", conn=None, host=None, username=None, password=None
@ -269,26 +192,9 @@ def mkdirs(path, share="C$", conn=None, host=None, username=None, password=None)
return _mkdirs_smbprotocol(
path, share, conn=conn, host=host, username=username, password=password
)
elif HAS_IMPACKET:
return _mkdirs_impacket(
path, share, conn=conn, host=host, username=username, password=password
)
raise MissingSmb("SMB library required (impacket or smbprotocol)")
def _put_str_impacket(
content, path, share="C$", conn=None, host=None, username=None, password=None
):
if conn is None:
conn = get_conn(host, username, password)
if conn is False:
return False
fh_ = StrHandle(content)
conn.putFile(share, path, fh_.string)
def _put_str_smbprotocol(
content, path, share="C$", conn=None, host=None, username=None, password=None
):
@ -321,45 +227,9 @@ def put_str(
username=username,
password=password,
)
elif HAS_IMPACKET:
return _put_str_impacket(
content,
path,
share,
conn=conn,
host=host,
username=username,
password=password,
)
raise MissingSmb("SMB library required (impacket or smbprotocol)")
def _put_file_impacket(
local_path, path, share="C$", conn=None, host=None, username=None, password=None
):
"""
Wrapper around impacket.smbconnection.putFile() that allows a file to be
uploaded
Example usage:
import salt.utils.smb
smb_conn = salt.utils.smb.get_conn('10.0.0.45', 'vagrant', 'vagrant')
salt.utils.smb.put_file('/root/test.pdf', 'temp\\myfiles\\test1.pdf', conn=smb_conn)
"""
if conn is None:
conn = get_conn(host, username, password)
if conn is False:
return False
if hasattr(local_path, "read"):
conn.putFile(share, path, local_path)
return
with salt.utils.files.fopen(local_path, "rb") as fh_:
conn.putFile(share, path, fh_.read)
def _put_file_smbprotocol(
local_path,
path,
@ -413,29 +283,9 @@ def put_file(
username=username,
password=password,
)
elif HAS_IMPACKET:
return _put_file_impacket(
local_path,
path,
share,
conn=conn,
host=host,
username=username,
password=password,
)
raise MissingSmb("SMB library required (impacket or smbprotocol)")
def _delete_file_impacket(
path, share="C$", conn=None, host=None, username=None, password=None
):
if conn is None:
conn = get_conn(host, username, password)
if conn is False:
return False
conn.deleteFile(share, path)
def _delete_file_smbprotocol(
path, share="C$", conn=None, host=None, username=None, password=None
):
@ -475,23 +325,9 @@ def delete_file(path, share="C$", conn=None, host=None, username=None, password=
return _delete_file_smbprotocol(
path, share, conn=conn, host=host, username=username, password=password
)
elif HAS_IMPACKET:
return _delete_file_impacket(
path, share, conn=conn, host=host, username=username, password=password
)
raise MissingSmb("SMB library required (impacket or smbprotocol)")
def _delete_directory_impacket(
path, share="C$", conn=None, host=None, username=None, password=None
):
if conn is None:
conn = get_conn(host, username, password)
if conn is False:
return False
conn.deleteDirectory(share, path)
def _delete_directory_smbprotocol(
path, share="C$", conn=None, host=None, username=None, password=None
):
@ -533,8 +369,4 @@ def delete_directory(
return _delete_directory_smbprotocol(
path, share, conn=conn, host=host, username=username, password=password
)
elif HAS_IMPACKET:
return _delete_directory_impacket(
path, share, conn=conn, host=host, username=username, password=password
)
raise MissingSmb("SMB library required (impacket or smbprotocol)")

View file

@ -69,8 +69,7 @@ def which_smbd():
@skipIf(not which_smbd(), reason="smbd binary not found")
@skipIf(
any([not salt.utils.smb.HAS_IMPACKET, not salt.utils.smb.HAS_SMBPROTOCOL]),
'Either "impacket" or "smbprotocol" needs to be installed.',
not salt.utils.smb.HAS_SMBPROTOCOL, '"smbprotocol" needs to be installed.',
)
class TestSmb(TestCase):

View file

@ -161,7 +161,9 @@ class ClearReqTestCases(BaseZMQReqCase, ReqChannelMixin):
master_ip="localhost", master_port=self.minion_config["master_port"]
)
channel = salt.transport.Channel.factory(self.minion_config, master_uri=uri)
channel = salt.transport.client.ReqChannel.factory(
self.minion_config, master_uri=uri
)
self.assertIn("localhost", channel.master_uri)
del channel
@ -343,11 +345,7 @@ class AsyncReqMessageClientPoolTest(TestCase):
]
def tearDown(self):
with patch(
"salt.transport.zeromq.AsyncReqMessageClient.destroy",
MagicMock(return_value=None),
):
del self.original_message_clients
del self.original_message_clients
super(AsyncReqMessageClientPoolTest, self).tearDown()
def test_send(self):
@ -361,10 +359,6 @@ class AsyncReqMessageClientPoolTest(TestCase):
self.message_client_pool.message_clients[2].send.return_value = [1]
self.assertEqual([1], self.message_client_pool.send())
def test_destroy(self):
self.message_client_pool.destroy()
self.assertEqual([], self.message_client_pool.message_clients)
class ZMQConfigTest(TestCase):
def test_master_uri(self):