Ejemplo n.º 1
0
 def __init__(self, session):
     """
     Arguments:
         session: Specifies a session
     """
     self._accessImpl = RestAccess(session)
     self.session = session
Ejemplo n.º 2
0
    def __init__(self, controllerUrl, secure, timeout, requestFormat):
        """Initialize an AbstractSession instance.

        Args:
          controllerURL (str): The URL to reach the controller or fabric node
          secure (bool): Only used for https. If True the remote server will be
            verified for authenticity.  If False the remote server will not be
            verified for authenticity.
          timeout (int): Request timeout
          requestFormat (str): The format to send the request in.
            Valid values are xml or json.

        Raises:
          NotImplementedError: If the requestFormat is not valid
        """
        if requestFormat not in {'xml', 'json'}:
            raise NotImplementedError("requestFormat should be one of: %s" %
                                      {'xml', 'json'})
        self.__secure = secure
        self.__timeout = timeout
        self.__controllerUrl = controllerUrl
        if requestFormat == 'xml':
            self.__format = AbstractSession.XML_FORMAT
            self.__codec = XMLMoCodec()
        elif requestFormat == 'json':
            self.__format = AbstractSession.JSON_FORMAT
            self.__codec = JSONMoCodec()
        self._accessimpl = RestAccess(self)
Ejemplo n.º 3
0
    def __init__(self, session):
        """Initialize a MoDirectory instance

        Args:
          session (cobra.mit.session.AbstractSession): The session

        """
        self._accessImpl = RestAccess(session)
Ejemplo n.º 4
0
    def __init__(self, controllerUrl, secure, timeout, requestFormat):
        """Initialize an AbstractSession instance.

        Args:
          controllerURL (str): The URL to reach the controller or fabric node
          secure (bool): Only used for https. If True the remote server will be
            verified for authenticity.  If False the remote server will not be
            verified for authenticity.
          timeout (int): Request timeout
          requestFormat (str): The format to send the request in.
            Valid values are xml or json.

        Raises:
          NotImplementedError: If the requestFormat is not valid
        """
        if requestFormat not in {'xml', 'json'}:
            raise NotImplementedError("requestFormat should be one of: %s" %
                                      {'xml', 'json'})
        self.__secure = secure
        self.__timeout = timeout
        self.__controllerUrl = controllerUrl
        if requestFormat == 'xml':
            self.__format = AbstractSession.XML_FORMAT
            self.__codec = XMLMoCodec()
        elif requestFormat == 'json':
            self.__format = AbstractSession.JSON_FORMAT
            self.__codec = JSONMoCodec()
        self._accessimpl = RestAccess(self)
Ejemplo n.º 5
0
 def __init__(self, session):
     """
     Arguments:
         session: Specifies a session
     """
     self._accessImpl = RestAccess(session)
     self.session = session
Ejemplo n.º 6
0
class MoDirectory(object):
    """
    The MoDirectory class creates a connection to the APIC and the MIT.
    MoDirectory requires an existing session and endpoint.
    """
    def __init__(self, session):
        """
        Arguments:
            session: Specifies a session
        """
        self._accessImpl = RestAccess(session)
        self.session = session

    def login(self):
        """
        Creates a session to an APIC.
        """
        self._accessImpl.login()

    def logout(self):
        """
        Ends a session to an APIC.
        """
        self._accessImpl.logout()

    def reauth(self):
        """
        Re-authenticate this session with the current authentication cookie.
        This method can be used to extend the validity of a successful login
        credentials. This method may fail if the current session expired on
        the server side. If this method fails, the user must login again to
        authenticate and effectively create a new session.
        """
        self._accessImpl.refreshSession()

    def query(self, queryObject):
        """
        Queries the MIT for a specified object. The queryObject provides a
        variety of search options.
        """
        return self._accessImpl.get(queryObject)

    def commit(self, configObject, sync_wait_timeout=None):
        """
        Short-form commit operation for a configRequest
        """
        # If a sync_wait_timeout is specified, then we call the post_sync_wait
        # method of the accessImpl, otherwise call post method
        if sync_wait_timeout:
            return self._accessImpl.post_sync_wait(configObject,
                                                   timeout=sync_wait_timeout)
        else:
            return self._accessImpl.post(configObject)

    def lookupByDn(self, dnStrOrDn, **queryParams):
        """
        A short-form managed object (MO) query using the distinguished name(Dn)
        of the MO.

        Args:
          dnStrOrDn:   dn of the object to lookup
          queryParams: a dictionary including the properties to the
            added to the query.
        """
        dnQuery = DnQuery(dnStrOrDn)
        self.__setQueryParams(dnQuery, queryParams)
        mos = self.query(dnQuery)
        return mos[0] if mos else None

    def lookupByClass(self, classNames, parentDn=None, **queryParams):
        """
        A short-form managed object (MO) query by class.

        Args:
          classNames: Name of the class to lookup
          parentDn:   dn of the root object were to start search from (optional)
          queryParams: a dictionary including the properties to the
            added to the query.
        """
        if parentDn:
            dnQuery = DnQuery(parentDn)
            dnQuery.classFilter = classNames
            dnQuery.queryTarget = 'subtree'
            self.__setQueryParams(dnQuery, queryParams)
            mos = self.query(dnQuery)
        else:
            classQuery = ClassQuery(classNames)
            self.__setQueryParams(classQuery, queryParams)
            mos = self.query(classQuery)
        return mos

    def exists(self, dnStrOrDn):
        """Checks if managed object (MO) with given distinguished name (dn) is present or not

        Args:
          dnStrOrDn (str or cobra.mit.naming.Dn): A distinguished name as a
            :class:`cobra.mit.naming.Dn` or string

        Returns:
          bool: True, if MO is present, else False.
        """
        mo = self.lookupByDn(dnStrOrDn, subtreeInclude='count')
        return mo is not None and int(mo.count) > 0

    @staticmethod
    def __setQueryParams(query, queryParams):
        """Utility function to set the query parameters.

        Utility function used to set in the 'query' passed as
        argument, the 'queryParams' dictionary. The key in the
        dictionary will be used as the property name to set, with
        the value content.

        Args:
          query: query class to be modified
          queryParams: a dictionary including the properties to the
            added to the query.
        """
        for param, value in list(queryParams.items()):
            if value is not None:
                setattr(query, param, value)
Ejemplo n.º 7
0
class AbstractSession(object):

    """Abstract session class.

    Other sessions classes should derive from this class.

    Attributes:
      secure (bool): Only used for https. If True the remote server will be
        verified for authenticity.  If False the remote server will not be
        verified for authenticity - readonly

      timeout (int): Request timeout - readonly

      url (str): The APIC or fabric node URL - readonly

      formatType (str): The format type for the request - readonly

      formatStr (str): The format string for the request, either xml or json
        - readonly
    """

    XML_FORMAT, JSON_FORMAT = 0, 1

    def __init__(self, controllerUrl, secure, timeout, requestFormat):
        """Initialize an AbstractSession instance.

        Args:
          controllerURL (str): The URL to reach the controller or fabric node
          secure (bool): Only used for https. If True the remote server will be
            verified for authenticity.  If False the remote server will not be
            verified for authenticity.
          timeout (int): Request timeout
          requestFormat (str): The format to send the request in.
            Valid values are xml or json.

        Raises:
          NotImplementedError: If the requestFormat is not valid
        """
        if requestFormat not in {'xml', 'json'}:
            raise NotImplementedError("requestFormat should be one of: %s" %
                                      {'xml', 'json'})
        self.__secure = secure
        self.__timeout = timeout
        self.__controllerUrl = controllerUrl
        if requestFormat == 'xml':
            self.__format = AbstractSession.XML_FORMAT
            self.__codec = XMLMoCodec()
        elif requestFormat == 'json':
            self.__format = AbstractSession.JSON_FORMAT
            self.__codec = JSONMoCodec()
        self._accessimpl = RestAccess(self)

    @property
    def secure(self):
        """Get the secure value.

        Returns:
          bool: True if the certificate for remote device should be verified,
            False otherwise.
        """
        return self.__secure

    @property
    def timeout(self):
        """Get the request timeout value.

        Returns:
          int: The time a request is allowed to take before an error is raised.
        """
        return self.__timeout

    @property
    def url(self):
        """Get the URL for the remote system.

        Returns:
          str: The URl for the remote system.
        """
        return self.__controllerUrl

    @url.setter
    def url(self, url):
        """Set the URL for the remote system.

        This is primarily used to handle redirects.

        Args:
          url (str): The URL to use for the controller.
        """
        self.__controllerUrl = url

    @property
    def formatType(self):
        """Get the format type for this session.

        Returns:
          int: The format type represented as an integer
        """
        return self.__format

    @property
    def formatStr(self):
        """Get the format string for this session.

        Returns:
          str: The formatType represented as a string.  Currently this is
            either 'xml' or 'json'.
        """
        return 'xml' if self.__format == AbstractSession.XML_FORMAT else 'json'

    @property
    def codec(self):
        """Get the codec being used for this session.

        Returns:
          cobra.mit.codec.AbstractCodec: The codec being used for this session.
        """
        return self.__codec

    def login(self):
        """Login to the remote server.

        A generic login method that should be overridden by classes that derive
        from this class
        """
        pass

    def logout(self):
        """Logout from the remote server.

        A generic logout method that should be overridden by classes that
        derive from this class
        """
        pass

    def refresh(self):
        """Refresh the session to the remote server.

        A generic refresh method that should be overridden by classes that
        derive from this class
        """
        pass

    def get(self, queryObject):
        """Perform a query using the specified queryObject.

        Args:
          queryObject(cobra.mit.request.AbstractQuery): The query object to
            use for the query.

        Returns:
          cobra.mit.mo.Mo: The query response parsed into a managed object
        """
        return self._accessimpl.get(queryObject)

    def post(self, requestObject):
        """Perform a request using the specified requestObject.

        Args:
          requestObject(cobra.mit.request.AbstractRequest): The request object
            to use for the request.

        Returns:
          requests.response: The raw requests response.
        """
        return self._accessimpl.post(requestObject)
Ejemplo n.º 8
0
class MoDirectory(MoDirectoryType):

    """
    The MoDirectory class creates a connection to the APIC and the MIT.
    MoDirectory requires an existing session and endpoint.
    """

    def __init__(self, session):
        """
        Arguments:
            session: Specifies a session
        """
        self._accessImpl = RestAccess(session)
        self.session = session

    def login(self):
        """
        Creates a session to an APIC.
        """
        self._accessImpl.login()

    def logout(self):
        """
        Ends a session to an APIC.
        """
        self._accessImpl.logout()

    def reauth(self):
        """
        Re-authenticate this session with the current authentication cookie.
        This method can be used to extend the validity of a successful login
        credentials. This method may fail if the current session expired on
        the server side. If this method fails, the user must login again to
        authenticate and effectively create a new session.
        """
        self._accessImpl.refreshSession()

    def query(self, queryObject):
        """
        Queries the MIT for a specified object. The queryObject provides a
        variety of search options.
        """
        return self._accessImpl.get(queryObject)

    def commit(self, configObject):
        """
        Short-form commit operation for a configRequest
        """
        if configObject.getRootMo() is None:
            raise CommitError(0, "No mos in config request")
        return self._accessImpl.post(configObject)

    def lookupByDn(self, dnStrOrDn, **queryParams):
        """
        A short-form managed object (MO) query using the distinguished name(Dn)
        of the MO.

        Args:
          dnStrOrDn:   dn of the object to lookup
          queryParams: a dictionary including the properties to the
            added to the query.
        """
        dnQuery = DnQuery(dnStrOrDn)
        self.__setQueryParams(dnQuery, queryParams)
        mos = self.query(dnQuery)
        return mos[0] if mos else None

    def lookupByClass(self, classNames, parentDn=None, **queryParams):
        """
        A short-form managed object (MO) query by class.

        Args:
          classNames: Name of the class to lookup
          parentDn:   dn of the root object were to start search from (optional)
          queryParams: a dictionary including the properties to the
            added to the query.
        """
        if parentDn:
            dnQuery = DnQuery(parentDn)
            dnQuery.classFilter = classNames
            dnQuery.queryTarget = 'subtree'
            self.__setQueryParams(dnQuery, queryParams)
            mos = self.query(dnQuery)
        else:
            classQuery = ClassQuery(classNames)
            self.__setQueryParams(classQuery, queryParams)
            mos = self.query(classQuery)
        return mos

    def exists(self, dnStrOrDn):
        """Checks if managed object (MO) with given distinguished name (dn) is present or not

        Args:
          dnStrOrDn (str or cobra.mit.naming.Dn): A distinguished name as a
            :class:`cobra.mit.naming.Dn` or string

        Returns:
          bool: True, if MO is present, else False.
        """
        mo = self.lookupByDn(dnStrOrDn, subtreeInclude='count')
        return mo is not None and int(mo.count) > 0

    @staticmethod
    def __setQueryParams(query, queryParams):
        """Utility function to set the query parameters.

        Utility function used to set in the 'query' passed as
        argument, the 'queryParams' dictionary. The key in the
        dictionary will be used as the property name to set, with
        the value content.

        Args:
          query: query class to be modified
          queryParams: a dictionary including the properties to the
            added to the query.
        """
        for param, value in queryParams.iteritems():
            if value is not None:
                setattr(query, param, value)
Ejemplo n.º 9
0
class AbstractSession(object):
    """Abstract session class.

    Other sessions classes should derive from this class.

    Attributes:
      secure (bool): Only used for https. If True the remote server will be
        verified for authenticity.  If False the remote server will not be
        verified for authenticity - readonly

      timeout (int): Request timeout - readonly

      url (str): The APIC or fabric node URL - readonly

      formatType (str): The format type for the request - readonly

      formatStr (str): The format string for the request, either xml or json
        - readonly
    """

    XML_FORMAT, JSON_FORMAT = 0, 1

    def __init__(self, controllerUrl, secure, timeout, requestFormat):
        """Initialize an AbstractSession instance.

        Args:
          controllerURL (str): The URL to reach the controller or fabric node
          secure (bool): Only used for https. If True the remote server will be
            verified for authenticity.  If False the remote server will not be
            verified for authenticity.
          timeout (int): Request timeout
          requestFormat (str): The format to send the request in.
            Valid values are xml or json.

        Raises:
          NotImplementedError: If the requestFormat is not valid
        """
        if requestFormat not in {'xml', 'json'}:
            raise NotImplementedError("requestFormat should be one of: %s" %
                                      {'xml', 'json'})
        self.__secure = secure
        self.__timeout = timeout
        self.__controllerUrl = controllerUrl
        if requestFormat == 'xml':
            self.__format = AbstractSession.XML_FORMAT
            self.__codec = XMLMoCodec()
        elif requestFormat == 'json':
            self.__format = AbstractSession.JSON_FORMAT
            self.__codec = JSONMoCodec()
        self._accessimpl = RestAccess(self)

    @property
    def secure(self):
        """Get the secure value.

        Returns:
          bool: True if the certificate for remote device should be verified,
            False otherwise.
        """
        return self.__secure

    @property
    def timeout(self):
        """Get the request timeout value.

        Returns:
          int: The time a request is allowed to take before an error is raised.
        """
        return self.__timeout

    @property
    def url(self):
        """Get the URL for the remote system.

        Returns:
          str: The URl for the remote system.
        """
        return self.__controllerUrl

    @url.setter
    def url(self, url):
        """Set the URL for the remote system.

        This is primarily used to handle redirects.

        Args:
          url (str): The URL to use for the controller.
        """
        self.__controllerUrl = url

    @property
    def formatType(self):
        """Get the format type for this session.

        Returns:
          int: The format type represented as an integer
        """
        return self.__format

    @property
    def formatStr(self):
        """Get the format string for this session.

        Returns:
          str: The formatType represented as a string.  Currently this is
            either 'xml' or 'json'.
        """
        return 'xml' if self.__format == AbstractSession.XML_FORMAT else 'json'

    @property
    def codec(self):
        """Get the codec being used for this session.

        Returns:
          cobra.mit.codec.AbstractCodec: The codec being used for this session.
        """
        return self.__codec

    def login(self):
        """Login to the remote server.

        A generic login method that should be overridden by classes that derive
        from this class
        """
        pass

    def logout(self):
        """Logout from the remote server.

        A generic logout method that should be overridden by classes that
        derive from this class
        """
        pass

    def refresh(self):
        """Refresh the session to the remote server.

        A generic refresh method that should be overridden by classes that
        derive from this class
        """
        pass

    def get(self, queryObject):
        """Perform a query using the specified queryObject.

        Args:
          queryObject(cobra.mit.request.AbstractQuery): The query object to
            use for the query.

        Returns:
          cobra.mit.mo.Mo: The query response parsed into a managed object
        """
        return self._accessimpl.get(queryObject)

    def post(self, requestObject):
        """Perform a request using the specified requestObject.

        Args:
          requestObject(cobra.mit.request.AbstractRequest): The request object
            to use for the request.

        Returns:
          requests.response: The raw requests response.
        """
        return self._accessimpl.post(requestObject)
Ejemplo n.º 10
0
class MoDirectory(object):
    """Creates a connection to the APIC and the MIT.

    MoDirectory requires an existing session.

    """
    def __init__(self, session):
        """Initialize a MoDirectory instance

        Args:
          session (cobra.mit.session.AbstractSession): The session

        """
        self._accessImpl = RestAccess(session)

    def login(self):
        """Creates a session to an APIC."""
        self._accessImpl.login()

    def logout(self):
        """Ends a session to an APIC."""
        self._accessImpl.logout()

    def reauth(self):
        """Re-authenticate the session with the current authentication cookie.

        This method can be used to extend the validity of a successful login
        credentials. This method may fail if the current session expired on
        the server side. If this method fails, the user must login again to
        authenticate and effectively create a new session.
        """
        self._accessImpl.refreshSession()

    def query(self, queryObject):
        """Queries the Model Information Tree.

        The various types of potential queryObjects provide a variety of
        search options

        Args:
          queryObject (cobra.mit.request.AbstractRequest): A query object

        Returns:
          list: A list of Managed Objects (MOs) returned from the query
        """
        return self._accessImpl.get(queryObject)

    def commit(self, configObject):
        """Commit operation for a request object.

        Commit a change on the APIC or fabric node.

        Args:
          configObject (cobra.mit.request.AbstractRequest): The configuration
            request to commit

        Returns:
          requests.response:  The response.
          
            .. note::
               This is different behavior than the query method.

        Raises:
          CommitError: If no MOs have been added to the config request
        """
        return self._accessImpl.post(configObject)

    def lookupByDn(self, dnStrOrDn):
        """Query the APIC or fabric node by distinguished name (Dn)
        
        A short-form managed object (MO) query using the Dn of the MO
        of the MO.

        Args:
          dnStrOrDn (str or cobra.mit.naming.Dn): A distinguished name as a
            :class:`cobra.mit.naming.Dn` or string

        Returns:
          None or cobra.mit.mo.Mo: None if no MO was returned otherwise
            :class:`cobra.mit.mo.Mo`
        """
        dnQuery = DnQuery(dnStrOrDn)
        mos = self.query(dnQuery)
        return mos[0] if mos else None

    def lookupByClass(self, classNames, parentDn=None, propFilter=None):
        """Lookup MO's by class

        A short-form managed object (MO) query by class.

        Args:
          classNames (str or list): The class name list of class names.
            If parentDn is set, the classNames are used as a filter in a
            subtree query for the parentDn
          parentDn (cobra.mit.naming.Dn or str): The distinguished
            name of the parent object as a :class:`cobra.mit.naming.Dn` or
            string.
          propFilter (str): A property filter expression

        Returns:
          list: A list of the managed objects found in the query.
        """
        if parentDn:
            dnQuery = DnQuery(parentDn)
            dnQuery.classFilter = classNames
            dnQuery.queryTarget = 'subtree'
            if propFilter:
                dnQuery.propFilter = propFilter
            mos = self.query(dnQuery)
        else:
            classQuery = ClassQuery(classNames)
            if propFilter:
                classQuery.propFilter = propFilter
            mos = self.query(classQuery)
        return mos