Exemple #1
0
    def connect(self):
        """
        Connect to the remote server.

        It is not normally necessary for a user to manually call this function,
        since when a connection is required, it is automatically created.

        Compared to base `Duct.connect`, this method will automatically catch
        the first `DuctAuthenticationError` error triggered by `Duct.connect`,
        and (if smartcards have been configured) attempt to re-initialise the
        smartcards before trying once more.

        Returns:
            `Duct` instance: A reference to the current object.
        """
        try:
            Duct.connect(self)
        except DuctServerUnreachable as e:
            raise_with_traceback(e)
        except DuctAuthenticationError as e:
            if self.smartcards and self.prepare_smartcards():
                Duct.connect(self)
            else:
                raise_with_traceback(e)
        return self
Exemple #2
0
    def __init__(self,
                 session_properties=None,
                 templates=None,
                 template_context=None,
                 default_format_opts=None,
                 **kwargs):
        """
        session_properties (dict): A mapping of default session properties
            to values. Interpretation is left up to implementations.
        templates (dict): A dictionary of name to template mappings. Additional
            templates can be added using `.template_add`.
        template_context (dict): The default template context to use when
            rendering templates.
        default_format_opts (dict): The default formatting options passed to
            cursor formatter.
        """
        Duct.__init_with_kwargs__(self, kwargs, port=self.DEFAULT_PORT)

        self.session_properties = session_properties or {}
        self._templates = templates or {}
        self._template_context = template_context or {}
        self._sqlalchemy_engine = None
        self._sqlalchemy_metadata = None
        self._default_format_opts = default_format_opts or {}

        self._init(**kwargs)
Exemple #3
0
    def connect(self):
        """
        This method causes the `Duct` instance to connect to the service, if it
        is not already connected. It is not normally necessary for a user to
        manually call this function, since when a connection is required, it is
        automatically created.

        Subclasses should implement `Duct._connect` to do whatever is necessary
        to bring a connection into being.

        Compared to base `Duct.connect`, this method will automatically catch
        the first `DuctAuthenticationError` error triggered by `Duct.connect`
        if any smartcards have been configured, before trying once more.

        Returns:
            `Duct` instance: A reference to the current object.
        """
        try:
            Duct.connect(self)
        except DuctServerUnreachable as e:
            raise_with_traceback(e)
        except DuctAuthenticationError as e:
            if self.smartcards and self.prepare_smartcards():
                Duct.connect(self)
            else:
                raise_with_traceback(e)
        return self
Exemple #4
0
 def __init__(self, **kwargs):
     """
     This is a shim __init__ function that passes all arguments onto
     `self._init`, which is implemented by subclasses. This allows subclasses
     to instantiate themselves with arbitrary parameters.
     """
     Duct.__init_with_kwargs__(self, kwargs)
     self._init(**kwargs)
Exemple #5
0
 def __init__(self, *args, **kwargs):
     '''
     This is a shim __init__ function that passes all arguments onto
     `self._init`, which is implemented by subclasses. This allows subclasses
     to instantiate themselves with arbitrary parameters.
     '''
     Duct.__init_with_kwargs__(self, kwargs, port=self.DEFAULT_PORT)
     self._init(*args, **kwargs)
Exemple #6
0
 def __init__(self, cwd=None, global_writes=False, **kwargs):
     """
     This is a shim __init__ function that passes all arguments onto
     `self._init`, which is implemented by subclasses. This allows subclasses
     to instantiate themselves with arbitrary parameters.
     """
     Duct.__init_with_kwargs__(self, kwargs, port=self.DEFAULT_PORT)
     self._path_cwd = cwd
     self.__path_home = None
     self.global_writes = global_writes
     self._init(**kwargs)
Exemple #7
0
 def __init__(self, cwd=None, global_writes=False, **kwargs):
     """
     This is a shim __init__ function that passes all arguments onto
     `self._init`, which is implemented by subclasses. This allows subclasses
     to instantiate themselves with arbitrary parameters.
     """
     Duct.__init_with_kwargs__(self, kwargs, port=self.DEFAULT_PORT)
     self._path_cwd = cwd
     self.__path_home = None
     self.global_writes = global_writes
     self._init(**kwargs)
Exemple #8
0
 def __init__(self, cwd=None, global_writes=False, **kwargs):
     """
     cwd (None, str): The path prefix to use as the current working directory
         (if None, the user's home directory is used where that makes sense).
     global_writes (bool): Whether to allow writes outside of the user's home
         folder.
     **kwargs (dict): Additional keyword arguments to passed on to subclasses.
     """
     Duct.__init_with_kwargs__(self, kwargs, port=self.DEFAULT_PORT)
     self._path_cwd = cwd
     self.__path_home = None
     self.global_writes = global_writes
     self._init(**kwargs)
Exemple #9
0
    def __init__(self, server_protocol='http', assume_json=False, endpoint_prefix='', **kwargs):
        """
        This is a shim __init__ function that passes all arguments onto
        `self._init`, which is implemented by subclasses. This allows subclasses
        to instantiate themselves with arbitrary parameters.
        """
        Duct.__init_with_kwargs__(self, kwargs, port=80)

        self.server_protocol = server_protocol
        self.assume_json = assume_json
        self.endpoint_prefix = endpoint_prefix

        self._init(**kwargs)
Exemple #10
0
    def __init__(self, *args, **kwargs):
        '''
        This is a shim __init__ function that passes all arguments onto
        `self._init`, which is implemented by subclasses. This allows subclasses
        to instantiate themselves with arbitrary parameters.
        '''
        Duct.__init_with_kwargs__(self, kwargs, port=self.DEFAULT_PORT)

        self._templates = kwargs.pop('templates', {})
        self._template_context = kwargs.pop('template_context', {})
        self._sqlalchemy_engine = None
        self._sqlalchemy_metadata = None

        self._init(*args, **kwargs)
Exemple #11
0
    def __init__(self, **kwargs):
        """
        templates (dict): A dictionary of name to template mappings. Additional
            templates can be added using `.template_add`.
        template_context (dict): The default template context to use when
            rendering templates.
        """
        Duct.__init_with_kwargs__(self, kwargs, port=self.DEFAULT_PORT)

        self._templates = kwargs.pop('templates', {})
        self._template_context = kwargs.pop('template_context', {})
        self._sqlalchemy_engine = None
        self._sqlalchemy_metadata = None

        self._init(**kwargs)
Exemple #12
0
 def lookup(self, name, kind=None):
     if kind and not isinstance(kind, Duct.Type):
         kind = Duct.Type(kind)
     r = self._registry[name]
     if kind and r.DUCT_TYPE != kind:
         raise KeyError("No duct called '{}' of kind '{}'.".format(name, kind.value))
     return r
Exemple #13
0
    def lookup(self, name, kind=None):
        """
        Look up an existing registered `Duct` by name and (optionally) kind.

        Args:
            name (str): The name of the `Duct` instance.
            kind (str, Duct.Type): The kind of `Duct` to which the lookup should
                be restricted.

        Returns:
            `Duct`: The looked up `Duct` instance.

        Raises:
            DuctNotFound: If no `Duct` can be found for requested name and/or
                type.
        """
        if kind and not isinstance(kind, Duct.Type):
            kind = Duct.Type(kind)
        if name not in self._registry:
            raise DuctNotFound(name)
        duct = self._registry[name]
        if kind and duct.DUCT_TYPE != kind:
            raise DuctNotFound(
                "Duct named '{}' exists, but is not of kind '{}'.".format(
                    name, kind.value))
        return duct
Exemple #14
0
    def populate_namespace(self, namespace=None, names=None, kinds=None):
        """
        Populate a nominated namespace with references to a subset of ducts.

        While a registry object is a great way to store and configure `Duct`
        instances, it is sometimes desirable to surface frequently used
        instances in other more convenient namespaces (such as the globals of
        your module).

        Args:
            namespace (dict, None): The namespace to populate. If using from a
                module you can pass `globals()`. If `None`, a new dictionary is
                created, populated and then returned.
            names (list<str>, None): The names to include in the population. If
                not specified then all names will be exported.
            kinds (list<str>, None): The kinds of ducts to include in the
                population. If not specified, all kinds will be exported.

        Returns:
            dict: The populated namespace.
        """
        if namespace is None:
            namespace = {}
        if kinds is not None:
            kinds = [
                Duct.Type(kind) if not isinstance(kind, Duct.Type) else kind
                for kind in kinds
            ]
        for name, duct in self._registry.items():
            if (kinds is None or duct.DUCT_TYPE in kinds) and (names is None or
                                                               name in names):
                namespace[name.split('/')[-1]] = duct
        return namespace
Exemple #15
0
    def new(self,
            name,
            protocol,
            override=False,
            register_magics=True,
            **kwargs):
        """
        Create a new service and register it into the registry.

        Args:
            name (str): The name (or names) of the target service. If multiple
                aliases are to be used, names should be a comma separated list.
                See `.register` for more details.
            protocol (str): The protocol of the new service.
            override (bool): Whether to override any existing `Duct` instance
                of the same name. If `False`, any overrides will result in an
                exception.
            register_magics (bool): Whether to register the magics if running in
                and IPython session (default: `True`).
            **kwargs (dict): Additional arguments to pass to the constructor of
                the class associated with the nominated protocol.

        Returns:
            Duct: The `Duct` instance registered into the registry.
        """
        return self.register(Duct.for_protocol(protocol)(
            name=name.split(',')[0].strip(), registry=self, **kwargs),
                             name=name,
                             override=override,
                             register_magics=register_magics)
Exemple #16
0
    def __init__(self,
                 server_protocol='http',
                 assume_json=False,
                 endpoint_prefix='',
                 **kwargs):
        """
        This is a shim __init__ function that passes all arguments onto
        `self._init`, which is implemented by subclasses. This allows subclasses
        to instantiate themselves with arbitrary parameters.
        """
        Duct.__init_with_kwargs__(self, kwargs, port=80)

        self.server_protocol = server_protocol
        self.assume_json = assume_json
        self.endpoint_prefix = endpoint_prefix

        self._init(**kwargs)
Exemple #17
0
 def populate_namespace(self, namespace=None, include=None, kinds=None):
     if namespace is None:
         namespace = {}
     if kinds is not None:
         kinds = [Duct.Type(kind) if not isinstance(kind, Duct.Type) else kind for kind in kinds]
     for name, duct in self._registry.items():
         if (kinds is None or duct.DUCT_TYPE in kinds) and (include is None or name in include):
             namespace[name.split('/')[-1]] = duct
     return namespace
Exemple #18
0
    def __init__(self, session_properties=None, templates=None, template_context=None, **kwargs):
        """
        session_properties (dict): A mapping of default session properties
            to values. Interpretation is left up to implementations.
        templates (dict): A dictionary of name to template mappings. Additional
            templates can be added using `.template_add`.
        template_context (dict): The default template context to use when
            rendering templates.
        """
        Duct.__init_with_kwargs__(self, kwargs, port=self.DEFAULT_PORT)

        self.session_properties = session_properties or {}
        self._templates = templates or {}
        self._template_context = template_context or {}
        self._sqlalchemy_engine = None
        self._sqlalchemy_metadata = None

        self._init(**kwargs)
Exemple #19
0
 def new(self, names, protocol, register_magics=True, **options):
     if isinstance(names, six.string_types):
         names = names.split(',')
     duct = Duct.for_protocol(protocol)(name=names[0], registry=self, **options)
     for name in names:
         self.register(duct, name=name)
         if register_magics and isinstance(duct, MagicsProvider):
             duct.register_magics(base_name=name)
     return duct
Exemple #20
0
 def new(self, names, protocol, register_magics=True, **options):
     if isinstance(names, six.string_types):
         names = names.split(',')
     duct = Duct.for_protocol(protocol)(name=names[0], registry=self, **options)
     for name in names:
         self.register(duct, name=name)
         if register_magics and isinstance(duct, MagicsProvider):
             duct.register_magics(base_name=name)
     return duct
Exemple #21
0
    def connect(self):
        """
        If a connection to the ssh server does not already exist, calling
        this method creates it. It first attempts to connect directly. If it fails, it attempts to initialise and keys
        in case they had not already been initialised. (It does not do this before creating the connection so as to
        minimise needless re-preparation of the keys.

        NOTE: It is not normally necessary for a user to manually call this function,
        since when a connection is required, it is automatically made.
        """
        try:
            Duct.connect(self)
        except DuctServerUnreachable as e:
            raise_with_traceback(e)
        except DuctAuthenticationError as e:
            if self.smartcards and self.prepare_smartcards():
                Duct.connect(self)
            else:
                raise_with_traceback(e)
        return self
Exemple #22
0
    def __init__(self,
                 server_protocol='http',
                 assume_json=False,
                 endpoint_prefix='',
                 **kwargs):
        """
        Args:
            server_protocol (str): The protocol to use when connecting to the
                remote host (default: `'http'`).
            assume_json (bool): Assume that responses will be JSON when calling
                instances of this class (default: `False`).
            endpoint_prefix (str): The base_url path relative to the host at
                which the API is accessible (default: `''`).
            **kwargs (dict): Additional keyword arguments passed on to
                subclasses.
        """
        Duct.__init_with_kwargs__(self, kwargs, port=80)

        self.server_protocol = server_protocol
        self.assume_json = assume_json
        self.endpoint_prefix = endpoint_prefix

        self._init(**kwargs)
Exemple #23
0
 def __init__(self,
              cwd=None,
              home=None,
              read_only=False,
              global_writes=False,
              **kwargs):
     """
     cwd (None, str): The path prefix to use as the current working directory
         (if None, the user's home directory is used where that makes sense).
     home (None, str): The path prefix to use as the current users' home
         directory. If not specified, it will default to an implementation-
         specific value (often '/').
     read_only (bool): Whether the filesystem should only be able to perform
         read operations.
     global_writes (bool): Whether to allow writes outside of the user's home
         folder.
     **kwargs (dict): Additional keyword arguments to passed on to subclasses.
     """
     Duct.__init_with_kwargs__(self, kwargs, port=self.DEFAULT_PORT)
     self._path_cwd = cwd
     self.__path_home = home
     self.read_only = read_only
     self.global_writes = global_writes
     self._init(**kwargs)
Exemple #24
0
    def __init__(self, smartcards=None, **kwargs):
        """
        Create a new SSHClient.

        Parameters
        ----------
        host : string
            Remote host for ssh.
        user : string
            User name for ssh.
        kwargs : dict
            Extra parameters passed on to SSHClient._init, as implemented by subclasses.

        Returns
        -------
        self : SSHClient
            An SSHClient object with the connection details specified.
        """
        Duct.__init_with_kwargs__(self, kwargs, port=22)

        self.smartcards = smartcards
        self.__port_forwarding_register = PortForwardingRegister()

        self._init(**kwargs)
Exemple #25
0
 def __init__(self, **kwargs):
     Duct.__init_with_kwargs__(self, kwargs)
     self._init(**kwargs)
Exemple #26
0
 def __init__(self, **kwargs):
     Duct.__init_with_kwargs__(self, kwargs)
     self._init(**kwargs)