Address some pylint issues (#1155)

* Address cyclic-import.

* Address redefined-builtin.

* Address redefined-argument-from-local.

* Address many redefined-outer-name.

* Address pointless-string-statement.

* No longer needed due to separate bugfix.

* Address useless-return.

* Address possibly-used-before-assignment.

* Add TODOs.

* Address super-init-not-called.

* Address function-redefined.

* Address unspecified-encoding.

* Clean up more imports.
This commit is contained in:
Felix Fontein
2025-10-09 20:11:36 +02:00
committed by GitHub
parent db09affaea
commit a3efa26e2e
42 changed files with 348 additions and 323 deletions
+2 -2
View File
@@ -86,13 +86,13 @@ except ImportError:
def fail_on_missing_imports():
if REQUESTS_IMPORT_ERROR is not None:
from .errors import MissingRequirementException
from .errors import MissingRequirementException # pylint: disable=cyclic-import
raise MissingRequirementException(
"You have to install requests", "requests", REQUESTS_IMPORT_ERROR
)
if URLLIB3_IMPORT_ERROR is not None:
from .errors import MissingRequirementException
from .errors import MissingRequirementException # pylint: disable=cyclic-import
raise MissingRequirementException(
"You have to install urllib3", "urllib3", URLLIB3_IMPORT_ERROR
+13 -13
View File
@@ -289,14 +289,14 @@ class APIClient(_Session, DaemonApiMixin):
except _HTTPError as e:
create_api_error_from_http_exception(e)
def _result(self, response, json=False, binary=False):
if json and binary:
def _result(self, response, get_json=False, get_binary=False):
if get_json and get_binary:
raise AssertionError("json and binary must not be both True")
self._raise_for_status(response)
if json:
if get_json:
return response.json()
if binary:
if get_binary:
return response.content
return response.text
@@ -360,12 +360,12 @@ class APIClient(_Session, DaemonApiMixin):
else:
# Response is not chunked, meaning we probably
# encountered an error immediately
yield self._result(response, json=decode)
yield self._result(response, get_json=decode)
def _multiplexed_buffer_helper(self, response):
"""A generator of multiplexed data blocks read from a buffered
response."""
buf = self._result(response, binary=True)
buf = self._result(response, get_binary=True)
buf_length = len(buf)
walker = 0
while True:
@@ -478,7 +478,7 @@ class APIClient(_Session, DaemonApiMixin):
return (
self._stream_raw_result(res)
if stream
else self._result(res, binary=True)
else self._result(res, get_binary=True)
)
self._raise_for_status(res)
@@ -551,13 +551,13 @@ class APIClient(_Session, DaemonApiMixin):
def get_binary(self, pathfmt, *args, **kwargs):
return self._result(
self._get(self._url(pathfmt, *args, versioned_api=True), **kwargs),
binary=True,
get_binary=True,
)
def get_json(self, pathfmt, *args, **kwargs):
return self._result(
self._get(self._url(pathfmt, *args, versioned_api=True), **kwargs),
json=True,
get_json=True,
)
def get_text(self, pathfmt, *args, **kwargs):
@@ -581,7 +581,7 @@ class APIClient(_Session, DaemonApiMixin):
def delete_json(self, pathfmt, *args, **kwargs):
return self._result(
self._delete(self._url(pathfmt, *args, versioned_api=True), **kwargs),
json=True,
get_json=True,
)
def post_call(self, pathfmt, *args, **kwargs):
@@ -603,7 +603,7 @@ class APIClient(_Session, DaemonApiMixin):
self._post_json(
self._url(pathfmt, *args, versioned_api=True), data, **kwargs
),
binary=True,
get_binary=True,
)
def post_json_to_json(self, pathfmt, *args, **kwargs):
@@ -612,7 +612,7 @@ class APIClient(_Session, DaemonApiMixin):
self._post_json(
self._url(pathfmt, *args, versioned_api=True), data, **kwargs
),
json=True,
get_json=True,
)
def post_json_to_text(self, pathfmt, *args, **kwargs):
@@ -670,5 +670,5 @@ class APIClient(_Session, DaemonApiMixin):
def post_to_json(self, pathfmt, *args, **kwargs):
return self._result(
self._post(self._url(pathfmt, *args, versioned_api=True), **kwargs),
json=True,
get_json=True,
)
+4 -4
View File
@@ -33,7 +33,7 @@ class DaemonApiMixin(object):
If the server returns an error.
"""
url = self._url("/system/df")
return self._result(self._get(url), True)
return self._result(self._get(url), get_json=True)
def info(self):
"""
@@ -47,7 +47,7 @@ class DaemonApiMixin(object):
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
return self._result(self._get(self._url("/info")), True)
return self._result(self._get(self._url("/info")), get_json=True)
def login(
self,
@@ -108,7 +108,7 @@ class DaemonApiMixin(object):
response = self._post_json(self._url("/auth"), data=req_data)
if response.status_code == 200:
self._auth_configs.add_auth(registry or auth.INDEX_NAME, req_data)
return self._result(response, json=True)
return self._result(response, get_json=True)
def ping(self):
"""
@@ -137,4 +137,4 @@ class DaemonApiMixin(object):
If the server returns an error.
"""
url = self._url("/version", versioned_api=api_version)
return self._result(self._get(url), json=True)
return self._result(self._get(url), get_json=True)
+2 -2
View File
@@ -166,7 +166,7 @@ class AuthConfig(dict):
if not config_file:
return cls({}, credstore_env)
try:
with open(config_file) as f:
with open(config_file, "rt", encoding="utf-8") as f:
config_dict = json.load(f)
except (IOError, KeyError, ValueError) as e:
# Likely missing new Docker config file or it is in an
@@ -351,7 +351,7 @@ def _load_legacy_config(config_file):
log.debug("Attempting to parse legacy auth file format")
try:
data = []
with open(config_file) as f:
with open(config_file, "rt", encoding="utf-8") as f:
for line in f.readlines():
data.append(line.strip().split(" = ")[1])
if len(data) < 2:
+1 -1
View File
@@ -151,7 +151,7 @@ class ContextAPI(object):
if filename == METAFILE:
filepath = os.path.join(dirname, filename)
try:
with open(filepath, "r") as f:
with open(filepath, "rt", encoding="utf-8") as f:
data = json.load(f)
name = data["Name"]
if name == "default":
+3 -3
View File
@@ -32,7 +32,7 @@ def get_current_context_name_with_source():
docker_cfg_path = find_config_file()
if docker_cfg_path:
try:
with open(docker_cfg_path) as f:
with open(docker_cfg_path, "rt", encoding="utf-8") as f:
return (
json.load(f).get("currentContext", "default"),
f"configuration file {docker_cfg_path}",
@@ -53,7 +53,7 @@ def write_context_name_to_docker_config(name=None):
config = {}
if docker_cfg_path:
try:
with open(docker_cfg_path) as f:
with open(docker_cfg_path, "rt", encoding="utf-8") as f:
config = json.load(f)
except Exception as e:
return e
@@ -67,7 +67,7 @@ def write_context_name_to_docker_config(name=None):
if not docker_cfg_path:
docker_cfg_path = get_default_config_file()
try:
with open(docker_cfg_path, "w") as f:
with open(docker_cfg_path, "wt", encoding="utf-8") as f:
json.dump(config, f, indent=4)
except Exception as e:
return e
+2 -2
View File
@@ -133,7 +133,7 @@ class Context(object):
metadata = {}
try:
with open(meta_file) as f:
with open(meta_file, "rt", encoding="utf-8") as f:
metadata = json.load(f)
except (OSError, KeyError, ValueError) as e:
# unknown format
@@ -189,7 +189,7 @@ class Context(object):
meta_dir = get_meta_dir(self.name)
if not os.path.isdir(meta_dir):
os.makedirs(meta_dir)
with open(get_meta_file(self.name), "w") as f:
with open(get_meta_file(self.name), "wt", encoding="utf-8") as f:
f.write(json.dumps(self.Metadata))
tls_dir = get_tls_dir(self.name)
@@ -222,7 +222,7 @@ class SSHHTTPAdapter(BaseHTTPAdapter):
ssh_config_file = os.path.expanduser("~/.ssh/config")
if os.path.exists(ssh_config_file):
conf = paramiko.SSHConfig()
with open(ssh_config_file) as f:
with open(ssh_config_file, "rt", encoding="utf-8") as f:
conf.parse(f)
host_config = conf.lookup(base_url.hostname)
if "proxycommand" in host_config:
@@ -12,12 +12,6 @@
from __future__ import annotations
""" Resolves OpenSSL issues in some servers:
https://lukasa.co.uk/2013/01/Choosing_SSL_Version_In_Requests/
https://github.com/kennethreitz/requests/pull/799
"""
from ansible_collections.community.docker.plugins.module_utils._version import (
LooseVersion,
)
@@ -26,6 +20,11 @@ from .._import_helper import HTTPAdapter, urllib3
from .basehttpadapter import BaseHTTPAdapter
# Resolves OpenSSL issues in some servers:
# https://lukasa.co.uk/2013/01/Choosing_SSL_Version_In_Requests/
# https://github.com/kennethreitz/requests/pull/799
PoolManager = urllib3.poolmanager.PoolManager
+1 -1
View File
@@ -271,7 +271,7 @@ def process_dockerfile(dockerfile, path):
0
] or os.path.relpath(abs_dockerfile, path).startswith(".."):
# Dockerfile not in context - read data to insert into tar later
with open(abs_dockerfile) as df:
with open(abs_dockerfile, "rt", encoding="utf-8") as df:
return (f".dockerfile.{random.getrandbits(160):x}", df.read())
# Dockerfile is inside the context - return path relative to context root
+1 -1
View File
@@ -80,7 +80,7 @@ def load_general_config(config_path=None):
return {}
try:
with open(config_file) as f:
with open(config_file, "rt", encoding="utf-8") as f:
return json.load(f)
except (IOError, ValueError) as e:
# In the case of a legacy `.dockercfg` file, we will not
+2 -3
View File
@@ -10,9 +10,6 @@
# Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
# Do not use this from other collections or standalone plugins/modules!
from __future__ import annotations
"""Filename matching with shell patterns.
fnmatch(FILENAME, PATTERN) matches according to the local convention.
@@ -25,6 +22,8 @@ The function translate(PATTERN) returns a regular expression
corresponding to PATTERN. (It does not compile it.)
"""
from __future__ import annotations
import re
+1 -1
View File
@@ -452,7 +452,7 @@ def parse_env_file(env_file):
"""
environment = {}
with open(env_file, "r") as f:
with open(env_file, "rt", encoding="utf-8") as f:
for line in f:
if line[0] == "#":
+61 -41
View File
@@ -17,7 +17,7 @@ from collections.abc import Mapping, Sequence
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.parsing.convert_bool import BOOLEANS_FALSE, BOOLEANS_TRUE
from ansible_collections.community.docker.plugins.module_utils._util import ( # noqa: F401, pylint: disable=unused-import
from ansible_collections.community.docker.plugins.module_utils._util import (
DEFAULT_DOCKER_HOST,
DEFAULT_TIMEOUT_SECONDS,
DEFAULT_TLS,
@@ -101,14 +101,14 @@ if not HAS_DOCKER_PY:
# No Docker SDK for Python. Create a place holder client to allow
# instantiation of AnsibleModule and proper error handing
class Client(object): # noqa: F811
class Client(object): # noqa: F811, pylint: disable=function-redefined
def __init__(self, **kwargs):
pass
class APIError(Exception): # noqa: F811
class APIError(Exception): # noqa: F811, pylint: disable=function-redefined
pass
class NotFound(Exception): # noqa: F811
class NotFound(Exception): # noqa: F811, pylint: disable=function-redefined
pass
@@ -133,43 +133,45 @@ def _get_tls_config(fail_function, **kwargs):
fail_function(f"TLS config error: {exc}")
def is_using_tls(auth):
return auth["tls_verify"] or auth["tls"]
def is_using_tls(auth_data):
return auth_data["tls_verify"] or auth_data["tls"]
def get_connect_params(auth, fail_function):
if is_using_tls(auth):
auth["docker_host"] = auth["docker_host"].replace("tcp://", "https://")
def get_connect_params(auth_data, fail_function):
if is_using_tls(auth_data):
auth_data["docker_host"] = auth_data["docker_host"].replace(
"tcp://", "https://"
)
result = dict(
base_url=auth["docker_host"],
version=auth["api_version"],
timeout=auth["timeout"],
base_url=auth_data["docker_host"],
version=auth_data["api_version"],
timeout=auth_data["timeout"],
)
if auth["tls_verify"]:
if auth_data["tls_verify"]:
# TLS with verification
tls_config = dict(
verify=True,
assert_hostname=auth["tls_hostname"],
assert_hostname=auth_data["tls_hostname"],
fail_function=fail_function,
)
if auth["cert_path"] and auth["key_path"]:
tls_config["client_cert"] = (auth["cert_path"], auth["key_path"])
if auth["cacert_path"]:
tls_config["ca_cert"] = auth["cacert_path"]
if auth_data["cert_path"] and auth_data["key_path"]:
tls_config["client_cert"] = (auth_data["cert_path"], auth_data["key_path"])
if auth_data["cacert_path"]:
tls_config["ca_cert"] = auth_data["cacert_path"]
result["tls"] = _get_tls_config(**tls_config)
elif auth["tls"]:
elif auth_data["tls"]:
# TLS without verification
tls_config = dict(
verify=False,
fail_function=fail_function,
)
if auth["cert_path"] and auth["key_path"]:
tls_config["client_cert"] = (auth["cert_path"], auth["key_path"])
if auth_data["cert_path"] and auth_data["key_path"]:
tls_config["client_cert"] = (auth_data["cert_path"], auth_data["key_path"])
result["tls"] = _get_tls_config(**tls_config)
if auth.get("use_ssh_client"):
if auth_data.get("use_ssh_client"):
if LooseVersion(docker_version) < LooseVersion("4.4.0"):
fail_function(
"use_ssh_client=True requires Docker SDK for Python 4.4.0 or newer"
@@ -258,16 +260,18 @@ class AnsibleDockerClientBase(Client):
pass
@staticmethod
def _get_value(param_name, param_value, env_variable, default_value, type="str"):
def _get_value(
param_name, param_value, env_variable, default_value, value_type="str"
):
if param_value is not None:
# take module parameter value
if type == "bool":
if value_type == "bool":
if param_value in BOOLEANS_TRUE:
return True
if param_value in BOOLEANS_FALSE:
return False
return bool(param_value)
if type == "int":
if value_type == "int":
return int(param_value)
return param_value
@@ -281,13 +285,13 @@ class AnsibleDockerClientBase(Client):
return os.path.join(env_value, "ca.pem")
if param_name == "key_path":
return os.path.join(env_value, "key.pem")
if type == "bool":
if value_type == "bool":
if env_value in BOOLEANS_TRUE:
return True
if env_value in BOOLEANS_FALSE:
return False
return bool(env_value)
if type == "int":
if value_type == "int":
return int(env_value)
return env_value
@@ -317,50 +321,66 @@ class AnsibleDockerClientBase(Client):
params["docker_host"],
"DOCKER_HOST",
DEFAULT_DOCKER_HOST,
type="str",
value_type="str",
),
tls_hostname=self._get_value(
"tls_hostname",
params["tls_hostname"],
"DOCKER_TLS_HOSTNAME",
None,
type="str",
value_type="str",
),
api_version=self._get_value(
"api_version",
params["api_version"],
"DOCKER_API_VERSION",
"auto",
type="str",
value_type="str",
),
cacert_path=self._get_value(
"cacert_path", params["ca_path"], "DOCKER_CERT_PATH", None, type="str"
"cacert_path",
params["ca_path"],
"DOCKER_CERT_PATH",
None,
value_type="str",
),
cert_path=self._get_value(
"cert_path", params["client_cert"], "DOCKER_CERT_PATH", None, type="str"
"cert_path",
params["client_cert"],
"DOCKER_CERT_PATH",
None,
value_type="str",
),
key_path=self._get_value(
"key_path", params["client_key"], "DOCKER_CERT_PATH", None, type="str"
"key_path",
params["client_key"],
"DOCKER_CERT_PATH",
None,
value_type="str",
),
tls=self._get_value(
"tls", params["tls"], "DOCKER_TLS", DEFAULT_TLS, type="bool"
"tls", params["tls"], "DOCKER_TLS", DEFAULT_TLS, value_type="bool"
),
tls_verify=self._get_value(
"validate_certs",
params["validate_certs"],
"DOCKER_TLS_VERIFY",
DEFAULT_TLS_VERIFY,
type="bool",
value_type="bool",
),
timeout=self._get_value(
"timeout",
params["timeout"],
"DOCKER_TIMEOUT",
DEFAULT_TIMEOUT_SECONDS,
type="int",
value_type="int",
),
use_ssh_client=self._get_value(
"use_ssh_client", params["use_ssh_client"], None, False, type="bool"
"use_ssh_client",
params["use_ssh_client"],
None,
False,
value_type="bool",
),
)
@@ -561,7 +581,7 @@ class AnsibleDockerClientBase(Client):
break
return images
def pull_image(self, name, tag="latest", platform=None):
def pull_image(self, name, tag="latest", image_platform=None):
"""
Pull an image
"""
@@ -570,8 +590,8 @@ class AnsibleDockerClientBase(Client):
stream=True,
decode=True,
)
if platform is not None:
kwargs["platform"] = platform
if image_platform is not None:
kwargs["platform"] = image_platform
self.log(f"Pulling image {name}:{tag}")
old_tag = self.find_image(name, tag)
try:
@@ -606,7 +626,7 @@ class AnsibleDockerClientBase(Client):
self._url("/distribution/{0}/json", image),
headers={"X-Registry-Auth": header},
),
json=True,
get_json=True,
)
return super(AnsibleDockerClientBase, self).inspect_distribution(
image, **kwargs
+37 -19
View File
@@ -46,7 +46,7 @@ from ansible_collections.community.docker.plugins.module_utils._api.utils.utils
convert_filters,
parse_repository_tag,
)
from ansible_collections.community.docker.plugins.module_utils._util import ( # noqa: F401, pylint: disable=unused-import
from ansible_collections.community.docker.plugins.module_utils._util import (
DEFAULT_DOCKER_HOST,
DEFAULT_TIMEOUT_SECONDS,
DEFAULT_TLS,
@@ -151,16 +151,18 @@ class AnsibleDockerClientBase(Client):
pass
@staticmethod
def _get_value(param_name, param_value, env_variable, default_value, type="str"):
def _get_value(
param_name, param_value, env_variable, default_value, value_type="str"
):
if param_value is not None:
# take module parameter value
if type == "bool":
if value_type == "bool":
if param_value in BOOLEANS_TRUE:
return True
if param_value in BOOLEANS_FALSE:
return False
return bool(param_value)
if type == "int":
if value_type == "int":
return int(param_value)
return param_value
@@ -174,13 +176,13 @@ class AnsibleDockerClientBase(Client):
return os.path.join(env_value, "ca.pem")
if param_name == "key_path":
return os.path.join(env_value, "key.pem")
if type == "bool":
if value_type == "bool":
if env_value in BOOLEANS_TRUE:
return True
if env_value in BOOLEANS_FALSE:
return False
return bool(env_value)
if type == "int":
if value_type == "int":
return int(env_value)
return env_value
@@ -210,50 +212,66 @@ class AnsibleDockerClientBase(Client):
params["docker_host"],
"DOCKER_HOST",
DEFAULT_DOCKER_HOST,
type="str",
value_type="str",
),
tls_hostname=self._get_value(
"tls_hostname",
params["tls_hostname"],
"DOCKER_TLS_HOSTNAME",
None,
type="str",
value_type="str",
),
api_version=self._get_value(
"api_version",
params["api_version"],
"DOCKER_API_VERSION",
"auto",
type="str",
value_type="str",
),
cacert_path=self._get_value(
"cacert_path", params["ca_path"], "DOCKER_CERT_PATH", None, type="str"
"cacert_path",
params["ca_path"],
"DOCKER_CERT_PATH",
None,
value_type="str",
),
cert_path=self._get_value(
"cert_path", params["client_cert"], "DOCKER_CERT_PATH", None, type="str"
"cert_path",
params["client_cert"],
"DOCKER_CERT_PATH",
None,
value_type="str",
),
key_path=self._get_value(
"key_path", params["client_key"], "DOCKER_CERT_PATH", None, type="str"
"key_path",
params["client_key"],
"DOCKER_CERT_PATH",
None,
value_type="str",
),
tls=self._get_value(
"tls", params["tls"], "DOCKER_TLS", DEFAULT_TLS, type="bool"
"tls", params["tls"], "DOCKER_TLS", DEFAULT_TLS, value_type="bool"
),
tls_verify=self._get_value(
"validate_certs",
params["validate_certs"],
"DOCKER_TLS_VERIFY",
DEFAULT_TLS_VERIFY,
type="bool",
value_type="bool",
),
timeout=self._get_value(
"timeout",
params["timeout"],
"DOCKER_TIMEOUT",
DEFAULT_TIMEOUT_SECONDS,
type="int",
value_type="int",
),
use_ssh_client=self._get_value(
"use_ssh_client", params["use_ssh_client"], None, False, type="bool"
"use_ssh_client",
params["use_ssh_client"],
None,
False,
value_type="bool",
),
)
@@ -477,7 +495,7 @@ class AnsibleDockerClientBase(Client):
except Exception as exc:
self.fail(f"Error inspecting image ID {image_id} - {exc}")
def pull_image(self, name, tag="latest", platform=None):
def pull_image(self, name, tag="latest", image_platform=None):
"""
Pull an image
"""
@@ -490,8 +508,8 @@ class AnsibleDockerClientBase(Client):
"tag": tag or image_tag or "latest",
"fromImage": repository,
}
if platform is not None:
params["platform"] = platform
if image_platform is not None:
params["platform"] = image_platform
headers = {}
header = auth.get_config_header(self, registry)
+1 -1
View File
@@ -17,7 +17,7 @@ from ansible.module_utils.common.text.converters import to_native
from ansible_collections.community.docker.plugins.module_utils._api.auth import (
resolve_repository_name,
)
from ansible_collections.community.docker.plugins.module_utils._util import ( # noqa: F401, pylint: disable=unused-import
from ansible_collections.community.docker.plugins.module_utils._util import (
DEFAULT_DOCKER_HOST,
DEFAULT_TLS,
DEFAULT_TLS_VERIFY,
+2 -2
View File
@@ -942,9 +942,9 @@ class BaseComposeManager(DockerBaseClass):
result.pop(res)
def cleanup(self):
for dir in self.cleanup_dirs:
for directory in self.cleanup_dirs:
try:
shutil.rmtree(dir, True)
shutil.rmtree(directory, True)
except Exception:
# should not happen, but simply ignore to be on the safe side
pass
+98 -92
View File
@@ -53,19 +53,19 @@ _MOUNT_OPTION_TYPES = dict(
)
def _get_ansible_type(type):
if type == "set":
def _get_ansible_type(value_type):
if value_type == "set":
return "list"
if type not in ("list", "dict", "bool", "int", "float", "str"):
raise Exception(f'Invalid type "{type}"')
return type
if value_type not in ("list", "dict", "bool", "int", "float", "str"):
raise Exception(f'Invalid type "{value_type}"')
return value_type
class Option(object):
def __init__(
self,
name,
type,
value_type,
owner,
ansible_type=None,
elements=None,
@@ -81,9 +81,9 @@ class Option(object):
compare=None,
):
self.name = name
self.type = type
self.ansible_type = ansible_type or _get_ansible_type(type)
needs_elements = self.type in ("list", "set")
self.value_type = value_type
self.ansible_type = ansible_type or _get_ansible_type(value_type)
needs_elements = self.value_type in ("list", "set")
needs_ansible_elements = self.ansible_type in ("list",)
if elements is not None and not needs_elements:
raise Exception("elements only allowed for lists/sets")
@@ -118,7 +118,7 @@ class Option(object):
self.ansible_suboptions = ansible_suboptions if needs_suboptions else None
self.ansible_aliases = ansible_aliases or []
self.ansible_choices = ansible_choices
comparison_type = self.type
comparison_type = self.value_type
if comparison_type == "set" and self.elements == "dict":
comparison_type = "set(dict)"
elif comparison_type not in ("set", "list", "dict"):
@@ -330,7 +330,7 @@ class EngineDriver(object):
pass
@abc.abstractmethod
def pull_image(self, client, repository, tag, platform=None):
def pull_image(self, client, repository, tag, image_platform=None):
pass
@abc.abstractmethod
@@ -859,7 +859,7 @@ def _preprocess_ports(module, values):
else:
port_binds = len(container_ports) * [(ipaddr,)]
else:
module.fail_json(
return module.fail_json(
msg=f'Invalid port description "{port}" - expected 1 to 3 colon-separated parts, but got {p_len}. '
"Maybe you forgot to use square brackets ([...]) around an IPv6 address?"
)
@@ -920,55 +920,55 @@ def _compare_platform(option, param_value, container_value):
return param_value == container_value
OPTION_AUTO_REMOVE = OptionGroup().add_option("auto_remove", type="bool")
OPTION_AUTO_REMOVE = OptionGroup().add_option("auto_remove", value_type="bool")
OPTION_BLKIO_WEIGHT = OptionGroup().add_option("blkio_weight", type="int")
OPTION_BLKIO_WEIGHT = OptionGroup().add_option("blkio_weight", value_type="int")
OPTION_CAPABILITIES = OptionGroup().add_option(
"capabilities", type="set", elements="str"
"capabilities", value_type="set", elements="str"
)
OPTION_CAP_DROP = OptionGroup().add_option("cap_drop", type="set", elements="str")
OPTION_CAP_DROP = OptionGroup().add_option("cap_drop", value_type="set", elements="str")
OPTION_CGROUP_NS_MODE = OptionGroup().add_option(
"cgroupns_mode", type="str", ansible_choices=["private", "host"]
"cgroupns_mode", value_type="str", ansible_choices=["private", "host"]
)
OPTION_CGROUP_PARENT = OptionGroup().add_option("cgroup_parent", type="str")
OPTION_CGROUP_PARENT = OptionGroup().add_option("cgroup_parent", value_type="str")
OPTION_COMMAND = OptionGroup(preprocess=_preprocess_command).add_option(
"command", type="list", elements="str", ansible_type="raw"
"command", value_type="list", elements="str", ansible_type="raw"
)
OPTION_CPU_PERIOD = OptionGroup().add_option("cpu_period", type="int")
OPTION_CPU_PERIOD = OptionGroup().add_option("cpu_period", value_type="int")
OPTION_CPU_QUOTA = OptionGroup().add_option("cpu_quota", type="int")
OPTION_CPU_QUOTA = OptionGroup().add_option("cpu_quota", value_type="int")
OPTION_CPUSET_CPUS = OptionGroup().add_option("cpuset_cpus", type="str")
OPTION_CPUSET_CPUS = OptionGroup().add_option("cpuset_cpus", value_type="str")
OPTION_CPUSET_MEMS = OptionGroup().add_option("cpuset_mems", type="str")
OPTION_CPUSET_MEMS = OptionGroup().add_option("cpuset_mems", value_type="str")
OPTION_CPU_SHARES = OptionGroup().add_option("cpu_shares", type="int")
OPTION_CPU_SHARES = OptionGroup().add_option("cpu_shares", value_type="int")
OPTION_ENTRYPOINT = OptionGroup(preprocess=_preprocess_entrypoint).add_option(
"entrypoint", type="list", elements="str"
"entrypoint", value_type="list", elements="str"
)
OPTION_CPUS = OptionGroup().add_option("cpus", type="int", ansible_type="float")
OPTION_CPUS = OptionGroup().add_option("cpus", value_type="int", ansible_type="float")
OPTION_DETACH_INTERACTIVE = (
OptionGroup()
.add_option("detach", type="bool")
.add_option("interactive", type="bool")
.add_option("detach", value_type="bool")
.add_option("interactive", value_type="bool")
)
OPTION_DEVICES = OptionGroup().add_option(
"devices", type="set", elements="dict", ansible_elements="str"
"devices", value_type="set", elements="dict", ansible_elements="str"
)
OPTION_DEVICE_READ_BPS = OptionGroup().add_option(
"device_read_bps",
type="set",
value_type="set",
elements="dict",
ansible_suboptions=dict(
path=dict(required=True, type="str"),
@@ -978,7 +978,7 @@ OPTION_DEVICE_READ_BPS = OptionGroup().add_option(
OPTION_DEVICE_WRITE_BPS = OptionGroup().add_option(
"device_write_bps",
type="set",
value_type="set",
elements="dict",
ansible_suboptions=dict(
path=dict(required=True, type="str"),
@@ -988,7 +988,7 @@ OPTION_DEVICE_WRITE_BPS = OptionGroup().add_option(
OPTION_DEVICE_READ_IOPS = OptionGroup().add_option(
"device_read_iops",
type="set",
value_type="set",
elements="dict",
ansible_suboptions=dict(
path=dict(required=True, type="str"),
@@ -998,7 +998,7 @@ OPTION_DEVICE_READ_IOPS = OptionGroup().add_option(
OPTION_DEVICE_WRITE_IOPS = OptionGroup().add_option(
"device_write_iops",
type="set",
value_type="set",
elements="dict",
ansible_suboptions=dict(
path=dict(required=True, type="str"),
@@ -1008,7 +1008,7 @@ OPTION_DEVICE_WRITE_IOPS = OptionGroup().add_option(
OPTION_DEVICE_REQUESTS = OptionGroup().add_option(
"device_requests",
type="set",
value_type="set",
elements="dict",
ansible_suboptions=dict(
capabilities=dict(type="list", elements="list"),
@@ -1020,29 +1020,33 @@ OPTION_DEVICE_REQUESTS = OptionGroup().add_option(
)
OPTION_DEVICE_CGROUP_RULES = OptionGroup().add_option(
"device_cgroup_rules", type="list", elements="str"
"device_cgroup_rules", value_type="list", elements="str"
)
OPTION_DNS_SERVERS = OptionGroup().add_option(
"dns_servers", type="list", elements="str"
"dns_servers", value_type="list", elements="str"
)
OPTION_DNS_OPTS = OptionGroup().add_option("dns_opts", type="set", elements="str")
OPTION_DNS_OPTS = OptionGroup().add_option("dns_opts", value_type="set", elements="str")
OPTION_DNS_SEARCH_DOMAINS = OptionGroup().add_option(
"dns_search_domains", type="list", elements="str"
"dns_search_domains", value_type="list", elements="str"
)
OPTION_DOMAINNAME = OptionGroup().add_option("domainname", type="str")
OPTION_DOMAINNAME = OptionGroup().add_option("domainname", value_type="str")
OPTION_ENVIRONMENT = (
OptionGroup(preprocess=_preprocess_env)
.add_option(
"env", type="set", ansible_type="dict", elements="str", needs_no_suboptions=True
"env",
value_type="set",
ansible_type="dict",
elements="str",
needs_no_suboptions=True,
)
.add_option(
"env_file",
type="set",
value_type="set",
ansible_type="path",
elements="str",
not_a_container_option=True,
@@ -1051,17 +1055,17 @@ OPTION_ENVIRONMENT = (
OPTION_ETC_HOSTS = OptionGroup().add_option(
"etc_hosts",
type="set",
value_type="set",
ansible_type="dict",
elements="str",
needs_no_suboptions=True,
)
OPTION_GROUPS = OptionGroup().add_option("groups", type="set", elements="str")
OPTION_GROUPS = OptionGroup().add_option("groups", value_type="set", elements="str")
OPTION_HEALTHCHECK = OptionGroup(preprocess=_preprocess_healthcheck).add_option(
"healthcheck",
type="dict",
value_type="dict",
ansible_suboptions=dict(
test=dict(type="raw"),
test_cli_compatible=dict(type="bool", default=False),
@@ -1073,69 +1077,71 @@ OPTION_HEALTHCHECK = OptionGroup(preprocess=_preprocess_healthcheck).add_option(
),
)
OPTION_HOSTNAME = OptionGroup().add_option("hostname", type="str")
OPTION_HOSTNAME = OptionGroup().add_option("hostname", value_type="str")
OPTION_IMAGE = OptionGroup().add_option("image", type="str")
OPTION_IMAGE = OptionGroup().add_option("image", value_type="str")
OPTION_INIT = OptionGroup().add_option("init", type="bool")
OPTION_INIT = OptionGroup().add_option("init", value_type="bool")
OPTION_IPC_MODE = OptionGroup().add_option("ipc_mode", type="str")
OPTION_IPC_MODE = OptionGroup().add_option("ipc_mode", value_type="str")
OPTION_KERNEL_MEMORY = OptionGroup(
preprocess=partial(_preprocess_convert_to_bytes, name="kernel_memory")
).add_option("kernel_memory", type="int", ansible_type="str")
).add_option("kernel_memory", value_type="int", ansible_type="str")
OPTION_LABELS = OptionGroup(preprocess=_preprocess_labels).add_option(
"labels", type="dict", needs_no_suboptions=True
"labels", value_type="dict", needs_no_suboptions=True
)
OPTION_LINKS = OptionGroup().add_option(
"links", type="set", elements="list", ansible_elements="str"
"links", value_type="set", elements="list", ansible_elements="str"
)
OPTION_LOG_DRIVER_OPTIONS = (
OptionGroup(
preprocess=_preprocess_log, ansible_required_by={"log_options": ["log_driver"]}
)
.add_option("log_driver", type="str")
.add_option("log_driver", value_type="str")
.add_option(
"log_options",
type="dict",
value_type="dict",
ansible_aliases=["log_opt"],
needs_no_suboptions=True,
)
)
OPTION_MAC_ADDRESS = OptionGroup(preprocess=_preprocess_mac_address).add_option(
"mac_address", type="str"
"mac_address", value_type="str"
)
OPTION_MEMORY = OptionGroup(
preprocess=partial(_preprocess_convert_to_bytes, name="memory")
).add_option("memory", type="int", ansible_type="str")
).add_option("memory", value_type="int", ansible_type="str")
OPTION_MEMORY_RESERVATION = OptionGroup(
preprocess=partial(_preprocess_convert_to_bytes, name="memory_reservation")
).add_option("memory_reservation", type="int", ansible_type="str")
).add_option("memory_reservation", value_type="int", ansible_type="str")
OPTION_MEMORY_SWAP = OptionGroup(
preprocess=partial(
_preprocess_convert_to_bytes, name="memory_swap", unlimited_value=-1
)
).add_option("memory_swap", type="int", ansible_type="str")
).add_option("memory_swap", value_type="int", ansible_type="str")
OPTION_MEMORY_SWAPPINESS = OptionGroup().add_option("memory_swappiness", type="int")
OPTION_MEMORY_SWAPPINESS = OptionGroup().add_option(
"memory_swappiness", value_type="int"
)
OPTION_STOP_TIMEOUT = OptionGroup().add_option(
"stop_timeout", type="int", default_comparison="ignore"
"stop_timeout", value_type="int", default_comparison="ignore"
)
OPTION_NETWORK = (
OptionGroup(preprocess=_preprocess_networks)
.add_option("network_mode", type="str")
.add_option("network_mode", value_type="str")
.add_option(
"networks",
type="set",
value_type="set",
elements="dict",
ansible_suboptions=dict(
name=dict(type="str", required=True),
@@ -1150,81 +1156,81 @@ OPTION_NETWORK = (
)
)
OPTION_OOM_KILLER = OptionGroup().add_option("oom_killer", type="bool")
OPTION_OOM_KILLER = OptionGroup().add_option("oom_killer", value_type="bool")
OPTION_OOM_SCORE_ADJ = OptionGroup().add_option("oom_score_adj", type="int")
OPTION_OOM_SCORE_ADJ = OptionGroup().add_option("oom_score_adj", value_type="int")
OPTION_PID_MODE = OptionGroup().add_option("pid_mode", type="str")
OPTION_PID_MODE = OptionGroup().add_option("pid_mode", value_type="str")
OPTION_PIDS_LIMIT = OptionGroup().add_option("pids_limit", type="int")
OPTION_PIDS_LIMIT = OptionGroup().add_option("pids_limit", value_type="int")
OPTION_PLATFORM = OptionGroup().add_option(
"platform", type="str", compare=_compare_platform
"platform", value_type="str", compare=_compare_platform
)
OPTION_PRIVILEGED = OptionGroup().add_option("privileged", type="bool")
OPTION_PRIVILEGED = OptionGroup().add_option("privileged", value_type="bool")
OPTION_READ_ONLY = OptionGroup().add_option("read_only", type="bool")
OPTION_READ_ONLY = OptionGroup().add_option("read_only", value_type="bool")
OPTION_RESTART_POLICY = (
OptionGroup(ansible_required_by={"restart_retries": ["restart_policy"]})
.add_option(
"restart_policy",
type="str",
value_type="str",
ansible_choices=["no", "on-failure", "always", "unless-stopped"],
)
.add_option("restart_retries", type="int")
.add_option("restart_retries", value_type="int")
)
OPTION_RUNTIME = OptionGroup().add_option("runtime", type="str")
OPTION_RUNTIME = OptionGroup().add_option("runtime", value_type="str")
OPTION_SECURITY_OPTS = OptionGroup().add_option(
"security_opts", type="set", elements="str"
"security_opts", value_type="set", elements="str"
)
OPTION_SHM_SIZE = OptionGroup(
preprocess=partial(_preprocess_convert_to_bytes, name="shm_size")
).add_option("shm_size", type="int", ansible_type="str")
).add_option("shm_size", value_type="int", ansible_type="str")
OPTION_STOP_SIGNAL = OptionGroup().add_option("stop_signal", type="str")
OPTION_STOP_SIGNAL = OptionGroup().add_option("stop_signal", value_type="str")
OPTION_STORAGE_OPTS = OptionGroup().add_option(
"storage_opts", type="dict", needs_no_suboptions=True
"storage_opts", value_type="dict", needs_no_suboptions=True
)
OPTION_SYSCTLS = OptionGroup(preprocess=_preprocess_sysctls).add_option(
"sysctls", type="dict", needs_no_suboptions=True
"sysctls", value_type="dict", needs_no_suboptions=True
)
OPTION_TMPFS = OptionGroup(preprocess=_preprocess_tmpfs).add_option(
"tmpfs", type="dict", ansible_type="list", ansible_elements="str"
"tmpfs", value_type="dict", ansible_type="list", ansible_elements="str"
)
OPTION_TTY = OptionGroup().add_option("tty", type="bool")
OPTION_TTY = OptionGroup().add_option("tty", value_type="bool")
OPTION_ULIMITS = OptionGroup(preprocess=_preprocess_ulimits).add_option(
"ulimits", type="set", elements="dict", ansible_elements="str"
"ulimits", value_type="set", elements="dict", ansible_elements="str"
)
OPTION_USER = OptionGroup().add_option("user", type="str")
OPTION_USER = OptionGroup().add_option("user", value_type="str")
OPTION_USERNS_MODE = OptionGroup().add_option("userns_mode", type="str")
OPTION_USERNS_MODE = OptionGroup().add_option("userns_mode", value_type="str")
OPTION_UTS = OptionGroup().add_option("uts", type="str")
OPTION_UTS = OptionGroup().add_option("uts", value_type="str")
OPTION_VOLUME_DRIVER = OptionGroup().add_option("volume_driver", type="str")
OPTION_VOLUME_DRIVER = OptionGroup().add_option("volume_driver", value_type="str")
OPTION_VOLUMES_FROM = OptionGroup().add_option(
"volumes_from", type="set", elements="str"
"volumes_from", value_type="set", elements="str"
)
OPTION_WORKING_DIR = OptionGroup().add_option("working_dir", type="str")
OPTION_WORKING_DIR = OptionGroup().add_option("working_dir", value_type="str")
OPTION_MOUNTS_VOLUMES = (
OptionGroup(preprocess=_preprocess_mounts)
.add_option(
"mounts",
type="set",
value_type="set",
elements="dict",
ansible_suboptions=dict(
target=dict(type="str", required=True),
@@ -1256,10 +1262,10 @@ OPTION_MOUNTS_VOLUMES = (
tmpfs_options=dict(type="list", elements="dict"),
),
)
.add_option("volumes", type="set", elements="str")
.add_option("volumes", value_type="set", elements="str")
.add_option(
"volume_binds",
type="set",
value_type="set",
elements="str",
not_an_ansible_option=True,
copy_comparison_from="volumes",
@@ -1270,21 +1276,21 @@ OPTION_PORTS = (
OptionGroup(preprocess=_preprocess_ports)
.add_option(
"exposed_ports",
type="set",
value_type="set",
elements="str",
ansible_aliases=["exposed", "expose"],
)
.add_option("publish_all_ports", type="bool")
.add_option("publish_all_ports", value_type="bool")
.add_option(
"published_ports",
type="dict",
value_type="dict",
ansible_type="list",
ansible_elements="str",
ansible_aliases=["ports"],
)
.add_option(
"ports",
type="set",
value_type="set",
elements="str",
not_an_ansible_option=True,
default_comparison="ignore",
@@ -119,12 +119,12 @@ _DEFAULT_IP_REPLACEMENT_STRING = (
)
def _get_ansible_type(type):
if type == "set":
def _get_ansible_type(our_type):
if our_type == "set":
return "list"
if type not in ("list", "dict", "bool", "int", "float", "str"):
raise Exception(f'Invalid type "{type}"')
return type
if our_type not in ("list", "dict", "bool", "int", "float", "str"):
raise Exception(f'Invalid type "{our_type}"')
return our_type
_SENTRY = object()
@@ -232,8 +232,8 @@ class DockerAPIEngineDriver(EngineDriver):
def inspect_image_by_name(self, client, repository, tag):
return client.find_image(repository, tag)
def pull_image(self, client, repository, tag, platform=None):
return client.pull_image(repository, tag, platform=platform)
def pull_image(self, client, repository, tag, image_platform=None):
return client.pull_image(repository, tag, image_platform=image_platform)
def pause_container(self, client, container_id):
client.post_call("/containers/{0}/pause", container_id)
@@ -892,8 +892,8 @@ def _preprocess_etc_hosts(module, client, api_version, value):
if value is None:
return value
results = []
for key, value in value.items():
results.append(f"{key}:{value}")
for key, val in value.items():
results.append(f"{key}:{val}")
return results
@@ -70,6 +70,7 @@ class Container(DockerBaseClass):
class ContainerManager(DockerBaseClass):
def __init__(self, module, engine_driver, client, active_options):
super().__init__()
self.module = module
self.engine_driver = engine_driver
self.client = client
@@ -569,7 +570,7 @@ class ContainerManager(DockerBaseClass):
self.client,
repository,
tag,
platform=self.module.params["platform"],
image_platform=self.module.params["platform"],
)
if alreadyToLatest:
self.results["changed"] = False
-14
View File
@@ -1,14 +0,0 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2024, Felix Fontein <felix@fontein.de>
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later
# Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
# Do not use this from other collections or standalone plugins/modules!
"""Provide selectors import."""
from __future__ import annotations
import selectors # noqa: F401, pylint: disable=unused-import
+4 -4
View File
@@ -56,7 +56,7 @@ class DockerSocketHandlerBase(object):
def __enter__(self):
return self
def __exit__(self, type, value, tb):
def __exit__(self, type_, value, tb):
self._selector.close()
def set_block_done_callback(self, block_done_callback):
@@ -204,9 +204,9 @@ class DockerSocketHandlerBase(object):
self.select()
return b"".join(stdout), b"".join(stderr)
def write(self, str):
self._write_buffer += str
if len(self._write_buffer) == len(str):
def write(self, str_to_write):
self._write_buffer += str_to_write
if len(self._write_buffer) == len(str_to_write):
self._write()
+1 -1
View File
@@ -111,7 +111,7 @@ def log_debug(msg, pretty_print=False):
If ``pretty_print=True``, the message will be pretty-printed as JSON.
"""
with open("docker.log", "a") as log_file:
with open("docker.log", "at", encoding="utf-8") as log_file:
if pretty_print:
log_file.write(
json.dumps(msg, sort_keys=True, indent=4, separators=(",", ": "))