From bde6f888a0547ca6f092ad4beb19316de22602d6 Mon Sep 17 00:00:00 2001 From: David Wilson Date: Thu, 1 Mar 2018 00:44:17 +0545 Subject: [PATCH] ansible: restructure package to avoid yet more madness Ansible's PluginLoader makes up bullshit when it imports a module (mostly because it has to make up something), therefore we ended up with duplicate copies of ansible_mitogen loaded: one under ansible.plugins.*.mitogen, and one under the canonical namespace. Which broke isinstance(). --- .../{connection/mitogen.py => connection.py} | 2 +- ansible_mitogen/connection/__init__.py | 0 .../actions/mitogen_async_status.py | 0 ansible_mitogen/plugins/connection/mitogen.py | 56 +++++++++++++++ ansible_mitogen/plugins/strategy/mitogen.py | 56 +++++++++++++++ ansible_mitogen/services.py | 72 +++++++++++++++++++ .../{strategy/mitogen.py => strategy.py} | 50 ++----------- ansible_mitogen/strategy/__init__.py | 0 8 files changed, 190 insertions(+), 46 deletions(-) rename ansible_mitogen/{connection/mitogen.py => connection.py} (99%) delete mode 100644 ansible_mitogen/connection/__init__.py rename ansible_mitogen/{ => plugins}/actions/mitogen_async_status.py (100%) create mode 100644 ansible_mitogen/plugins/connection/mitogen.py create mode 100644 ansible_mitogen/plugins/strategy/mitogen.py create mode 100644 ansible_mitogen/services.py rename ansible_mitogen/{strategy/mitogen.py => strategy.py} (83%) delete mode 100644 ansible_mitogen/strategy/__init__.py diff --git a/ansible_mitogen/connection/mitogen.py b/ansible_mitogen/connection.py similarity index 99% rename from ansible_mitogen/connection/mitogen.py rename to ansible_mitogen/connection.py index 79f286b7..c351a404 100644 --- a/ansible_mitogen/connection/mitogen.py +++ b/ansible_mitogen/connection.py @@ -39,7 +39,7 @@ import mitogen.unix from mitogen.utils import cast import ansible_mitogen.helpers -from ansible_mitogen.strategy.mitogen import ContextService +from ansible_mitogen.services import ContextService LOG = logging.getLogger(__name__) diff --git a/ansible_mitogen/connection/__init__.py b/ansible_mitogen/connection/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/ansible_mitogen/actions/mitogen_async_status.py b/ansible_mitogen/plugins/actions/mitogen_async_status.py similarity index 100% rename from ansible_mitogen/actions/mitogen_async_status.py rename to ansible_mitogen/plugins/actions/mitogen_async_status.py diff --git a/ansible_mitogen/plugins/connection/mitogen.py b/ansible_mitogen/plugins/connection/mitogen.py new file mode 100644 index 00000000..d9bdc5f6 --- /dev/null +++ b/ansible_mitogen/plugins/connection/mitogen.py @@ -0,0 +1,56 @@ +# Copyright 2017, David Wilson +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# 3. Neither the name of the copyright holder nor the names of its contributors +# may be used to endorse or promote products derived from this software without +# specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +import os.path +import sys + +# +# This is not the real Connection implementation module, it simply exists as a +# proxy to the real module, which is loaded using Python's regular import +# mechanism, to prevent Ansible's PluginLoader from making up a fake name that +# results in ansible_mitogen plugin modules being loaded twice: once by +# PluginLoader with a name like "ansible.plugins.connection.mitogen", which is +# stuffed into sys.modules even though attempting to import it will trigger an +# ImportError, and once under its canonical name, "ansible_mitogen.connection". +# +# Therefore we have a proxy module that imports it under the real name, and +# sets up the duff PluginLoader-imported module to just contain objects from +# the real module, so duplicate types don't exist in memory, and things like +# debuggers and isinstance() work predictably. +# + +try: + import ansible_mitogen +except ImportError: + base_dir = os.path.dirname(__file__) + sys.path.insert(0, os.path.abspath(os.path.join(base_dir, '../..'))) + del base_dir + +from ansible_mitogen.connection import Connection +del os +del sys diff --git a/ansible_mitogen/plugins/strategy/mitogen.py b/ansible_mitogen/plugins/strategy/mitogen.py new file mode 100644 index 00000000..6572c26f --- /dev/null +++ b/ansible_mitogen/plugins/strategy/mitogen.py @@ -0,0 +1,56 @@ +# Copyright 2017, David Wilson +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# 3. Neither the name of the copyright holder nor the names of its contributors +# may be used to endorse or promote products derived from this software without +# specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +import os.path +import sys + +# +# This is not the real Strategy implementation module, it simply exists as a +# proxy to the real module, which is loaded using Python's regular import +# mechanism, to prevent Ansible's PluginLoader from making up a fake name that +# results in ansible_mitogen plugin modules being loaded twice: once by +# PluginLoader with a name like "ansible.plugins.strategy.mitogen", which is +# stuffed into sys.modules even though attempting to import it will trigger an +# ImportError, and once under its canonical name, "ansible_mitogen.strategy". +# +# Therefore we have a proxy module that imports it under the real name, and +# sets up the duff PluginLoader-imported module to just contain objects from +# the real module, so duplicate types don't exist in memory, and things like +# debuggers and isinstance() work predictably. +# + +try: + import ansible_mitogen +except ImportError: + base_dir = os.path.dirname(__file__) + sys.path.insert(0, os.path.abspath(os.path.join(base_dir, '../..'))) + del base_dir + +from ansible_mitogen.strategy import StrategyModule +del os +del sys diff --git a/ansible_mitogen/services.py b/ansible_mitogen/services.py new file mode 100644 index 00000000..005f2d7a --- /dev/null +++ b/ansible_mitogen/services.py @@ -0,0 +1,72 @@ +# Copyright 2017, David Wilson +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# 3. Neither the name of the copyright holder nor the names of its contributors +# may be used to endorse or promote products derived from this software without +# specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +from __future__ import absolute_import +import mitogen.service + + +class ContextService(mitogen.service.Service): + """ + Used by worker processes connecting back into the top-level process to + fetch the single Context instance corresponding to the supplied connection + configuration, creating a matching connection if it does not exist. + + For connection methods and their parameters, refer to: + http://mitogen.readthedocs.io/en/latest/api.html#context-factories + + This concentrates all SSH connections in the top-level process, which may + become a bottleneck. There are multiple ways to fix that: + * creating one .local() child context per CPU and sharding connections + between them, using the master process to route messages, or + * as above, but having each child create a unique UNIX listener and + having workers connect in directly. + + :param dict dct: + Parameters passed to mitogen.master.Router.[method](). One key, + "method", is popped from the dictionary and used to look up the method. + + :returns mitogen.master.Context: + Corresponding Context instance. + """ + handle = 500 + max_message_size = 1000 + + def __init__(self, router): + super(ContextService, self).__init__(router) + self._context_by_key = {} + + def validate_args(self, args): + return isinstance(args, dict) + + def dispatch(self, dct, msg): + key = repr(sorted(dct.items())) + if key not in self._context_by_key: + method = getattr(self.router, dct.pop('method')) + self._context_by_key[key] = method(**dct) + return self._context_by_key[key] + diff --git a/ansible_mitogen/strategy/mitogen.py b/ansible_mitogen/strategy.py similarity index 83% rename from ansible_mitogen/strategy/mitogen.py rename to ansible_mitogen/strategy.py index 90bab41e..63fd58ae 100644 --- a/ansible_mitogen/strategy/mitogen.py +++ b/ansible_mitogen/strategy.py @@ -39,6 +39,7 @@ import mitogen.utils import ansible.errors import ansible.plugins.strategy.linear import ansible_mitogen.mixins +import ansible_mitogen.services try: from ansible.plugins.loader import action_loader @@ -90,47 +91,6 @@ def wrap_connection_loader__get(name, play_context, new_stdin): return connection_loader__get(name, play_context, new_stdin, **kwargs) -class ContextService(mitogen.service.Service): - """ - Used by worker processes connecting back into the top-level process to - fetch the single Context instance corresponding to the supplied connection - configuration, creating a matching connection if it does not exist. - - For connection methods and their parameters, refer to: - http://mitogen.readthedocs.io/en/latest/api.html#context-factories - - This concentrates all SSH connections in the top-level process, which may - become a bottleneck. There are multiple ways to fix that: - * creating one .local() child context per CPU and sharding connections - between them, using the master process to route messages, or - * as above, but having each child create a unique UNIX listener and - having workers connect in directly. - - :param dict dct: - Parameters passed to mitogen.master.Router.[method](). One key, - "method", is popped from the dictionary and used to look up the method. - - :returns mitogen.master.Context: - Corresponding Context instance. - """ - handle = 500 - max_message_size = 1000 - - def __init__(self, router): - super(ContextService, self).__init__(router) - self._context_by_key = {} - - def validate_args(self, args): - return isinstance(args, dict) - - def dispatch(self, dct, msg): - key = repr(sorted(dct.items())) - if key not in self._context_by_key: - method = getattr(self.router, dct.pop('method')) - self._context_by_key[key] = method(**dct) - return self._context_by_key[key] - - class StrategyModule(ansible.plugins.strategy.linear.StrategyModule): """ This strategy enhances the default "linear" strategy by arranging for @@ -207,7 +167,7 @@ class StrategyModule(ansible.plugins.strategy.linear.StrategyModule): Construct a ContextService and a thread to service requests for it arriving from worker processes. """ - self.service = ContextService(self.router) + self.service = ansible_mitogen.services.ContextService(self.router) self.service_thread = threading.Thread(target=self.service.run) self.service_thread.start() @@ -251,9 +211,9 @@ class StrategyModule(ansible.plugins.strategy.linear.StrategyModule): Add the mitogen connection plug-in directory to the ModuleLoader path, avoiding the need for manual configuration. """ - basedir = os.path.dirname(os.path.dirname(__file__)) - connection_loader.add_directory(os.path.join(basedir, 'connection')) - action_loader.add_directory(os.path.join(basedir, 'actions')) + base_dir = os.path.join(os.path.dirname(__file__), 'plugins') + connection_loader.add_directory(os.path.join(base_dir, 'connection')) + action_loader.add_directory(os.path.join(base_dir, 'actions')) def run(self, iterator, play_context, result=0): self._add_connection_plugin_path() diff --git a/ansible_mitogen/strategy/__init__.py b/ansible_mitogen/strategy/__init__.py deleted file mode 100644 index e69de29b..00000000