Пример #1
0
class RemoteClient(BaseClient):
    """Context manager for API workers to access remote varlink."""

    def __init__(self, context):
        """Construct RemoteCLient."""
        super().__init__(context)
        self._portal = Portal()

    def __enter__(self):
        """Context manager for API workers to access varlink."""
        tunnel = self._portal.get(self._context.uri)
        if tunnel is None:
            tunnel = Tunnel(self._context).bore()
            self._portal[self._context.uri] = tunnel

        try:
            self._client = VarlinkClient(address=self._context.uri)
            self._iface = self._client.open(self._context.interface)
            return self._iface
        except Exception:
            tunnel.close()
            raise

    def __exit__(self, e_type, e, e_traceback):
        """Cleanup context for RemoteClient."""
        if hasattr(self._client, 'close'):
            self._client.close()
        self._iface.close()

        # set timer to shutdown ssh tunnel
        # self._portal.get(self._context.uri).close()
        if isinstance(e, VarlinkError):
            raise error_factory(e)
Пример #2
0
class RemoteClient(BaseClient):
    """Context manager for API workers to access remote varlink."""
    def __init__(self, context):
        """Construct RemoteCLient."""
        super().__init__(context)
        self._portal = Portal()

    def __enter__(self):
        """Context manager for API workers to access varlink."""
        tunnel = self._portal.get(self._context.uri)
        if tunnel is None:
            tunnel = Tunnel(self._context).bore()
            self._portal[self._context.uri] = tunnel

        try:
            self._client = VarlinkClient(address=self._context.uri)
            self._iface = self._client.open(self._context.interface)
            return self._iface
        except Exception:
            tunnel.close()
            raise

    def __exit__(self, e_type, e, e_traceback):
        """Cleanup context for RemoteClient."""
        if hasattr(self._client, 'close'):
            self._client.close()
        self._iface.close()

        # set timer to shutdown ssh tunnel
        # self._portal.get(self._context.uri).close()
        if isinstance(e, VarlinkError):
            raise error_factory(e)
Пример #3
0
 def _podman(uri, interface):
     """Context manager for API children to access varlink."""
     client = VarlinkClient(address=uri)
     try:
         iface = client.open(interface)
         yield iface
     except VarlinkError as e:
         raise error_factory(e) from e
     finally:
         if hasattr(client, 'close'):
             client.close()
         iface.close()
Пример #4
0
class LocalClient(BaseClient):
    """Context manager for API workers to access varlink."""
    def __enter__(self):
        """Enter context for LocalClient."""
        self._client = VarlinkClient(address=self._context.uri)
        self._iface = self._client.open(self._context.interface)
        return self._iface

    def __exit__(self, e_type, e, e_traceback):
        """Cleanup context for LocalClient."""
        if hasattr(self._client, 'close'):
            self._client.close()
        self._iface.close()

        if isinstance(e, VarlinkError):
            raise error_factory(e)
Пример #5
0
class LocalClient(BaseClient):
    """Context manager for API workers to access varlink."""

    def __enter__(self):
        """Enter context for LocalClient."""
        self._client = VarlinkClient(address=self._context.uri)
        self._iface = self._client.open(self._context.interface)
        return self._iface

    def __exit__(self, e_type, e, e_traceback):
        """Cleanup context for LocalClient."""
        if hasattr(self._client, 'close'):
            self._client.close()
        self._iface.close()

        if isinstance(e, VarlinkError):
            raise error_factory(e)
Пример #6
0
 def open(self):
     """Open connection to podman service."""
     self._client = VarlinkClient(address=self._context.uri)
     self._iface = self._client.open(self._context.interface)
     logging.debug(
         "%s opened varlink connection %s",
         type(self).__name__,
         str(self._iface),
     )
     return self._iface
Пример #7
0
    def __enter__(self):
        """Context manager for API workers to access varlink."""
        tunnel = self._portal.get(self._context.uri)
        if tunnel is None:
            tunnel = Tunnel(self._context).bore()
            self._portal[self._context.uri] = tunnel

        try:
            self._client = VarlinkClient(address=self._context.uri)
            self._iface = self._client.open(self._context.interface)
            return self._iface
        except Exception:
            tunnel.close()
            raise
Пример #8
0
    def __enter__(self):
        """Context manager for API workers to access varlink."""
        tunnel = self._portal.get(self._context.uri)
        if tunnel is None:
            tunnel = Tunnel(self._context).bore()
            self._portal[self._context.uri] = tunnel

        try:
            self._client = VarlinkClient(address=self._context.uri)
            self._iface = self._client.open(self._context.interface)
            return self._iface
        except Exception:
            tunnel.close()
            raise
Пример #9
0
 def __enter__(self):
     """Enter context for LocalClient."""
     self._client = VarlinkClient(address=self._context.uri)
     self._iface = self._client.open(self._context.interface)
     return self._iface
Пример #10
0
 def __init__(self, varlink_uri):
     c = Client(address=varlink_uri)
     self.conn = c.open("io.projectatomic.podman")
Пример #11
0
class BaseClient:
    """Context manager for API workers to access varlink."""
    def __init__(self, context):
        """Construct Client."""
        self._client = None
        self._iface = None
        self._context = context

    def __call__(self):
        """Support being called for old API."""
        return self

    @classmethod
    def factory(cls, uri=None, interface="io.podman", **kwargs):
        """Construct a Client based on input."""
        log_level = os.environ.get("PODMAN_LOG_LEVEL")
        if log_level is not None:
            logging.basicConfig(level=logging.getLevelName(log_level.upper()))
            logging.debug(
                "Logging level set to %s",
                logging.getLevelName(logging.getLogger().getEffectiveLevel()),
            )

        if uri is None:
            raise ValueError("uri is required and cannot be None")
        if interface is None:
            raise ValueError("interface is required and cannot be None")

        unsupported = set(kwargs.keys()).difference((
            "uri",
            "interface",
            "remote_uri",
            "identity_file",
            "ignore_hosts",
            "known_hosts",
        ))
        if unsupported:
            raise ValueError("Unknown keyword arguments: {}".format(
                ", ".join(unsupported)))

        local_path = urlparse(uri).path
        if not local_path:
            raise ValueError("path is required for uri,"
                             ' expected format "unix://path_to_socket"')

        if kwargs.get("remote_uri") is None:
            return LocalClient(Context(uri, interface))

        required = ("{} is required, expected format"
                    ' "ssh://user@hostname[:port]/path_to_socket".')

        # Remote access requires the full tuple of information
        if kwargs.get("remote_uri") is None:
            raise ValueError(required.format("remote_uri"))

        remote = urlparse(kwargs["remote_uri"])
        if remote.username is None:
            raise ValueError(required.format("username"))
        if remote.path == "":
            raise ValueError(required.format("path"))
        if remote.hostname is None:
            raise ValueError(required.format("hostname"))

        return RemoteClient(
            Context(
                uri,
                interface,
                local_path,
                remote.path,
                remote.username,
                remote.hostname,
                remote.port,
                kwargs.get("identity_file"),
                kwargs.get("ignore_hosts"),
                kwargs.get("known_hosts"),
            ))

    def open(self):
        """Open connection to podman service."""
        self._client = VarlinkClient(address=self._context.uri)
        self._iface = self._client.open(self._context.interface)
        logging.debug(
            "%s opened varlink connection %s",
            type(self).__name__,
            str(self._iface),
        )
        return self._iface

    def close(self):
        """Close connection to podman service."""
        if hasattr(self._client, "close"):
            self._client.close()  # pylint: disable=no-member
        self._iface.close()
        logging.debug(
            "%s closed varlink connection %s",
            type(self).__name__,
            str(self._iface),
        )
Пример #12
0
import unittest
from varlink import (Client, VarlinkError)

address = "unix:/run/podman/io.projectatomic.podman"
client = Client(address=address)


def runErrorTest(tfunc):
    try:
        tfunc()
    except VarlinkError as e:
        return e.error() == "org.varlink.service.MethodNotImplemented"
    return False


class ContainersAPI(unittest.TestCase):
    def test_ListContainers(self):
        podman = client.open("io.projectatomic.podman")
        self.assertTrue(runErrorTest(podman.ListContainers))

    def test_CreateContainer(self):
        podman = client.open("io.projectatomic.podman")
        self.assertTrue(runErrorTest(podman.CreateContainer))

    def test_InspecContainer(self):
        podman = client.open("io.projectatomic.podman")
        self.assertTrue(runErrorTest(podman.InspectContainer))

    def test_ListContainerProcesses(self):
        podman = client.open("io.projectatomic.podman")
        self.assertTrue(runErrorTest(podman.ListContainerProcesses))
Пример #13
0
 def __enter__(self):
     """Enter context for LocalClient."""
     self._client = VarlinkClient(address=self._context.uri)
     self._iface = self._client.open(self._context.interface)
     return self._iface