def _login(self):
     ''' Make a POST request to CVP login authentication.
         An error can be raised from the post method call or the
         _is_good_response method call.  Any errors raised would be a good
         reason not to use this host.
         Raises:
             ConnectionError: A ConnectionError is raised if there was a
                 network problem (e.g. DNS failure, refused connection, etc)
             CvpApiError: A CvpApiError is raised if there was a JSON error.
             CvpRequestError: A CvpRequestError is raised if the request
                 is not properly constructed.
             CvpSessionLogOutError: A CvpSessionLogOutError is raised if
                 response from server indicates session was logged out.
             HTTPError: A HTTPError is raised if there was an invalid HTTP
                 response.
             ReadTimeout: A ReadTimeout is raised if there was a request
                 timeout when reading from the connection.
             Timeout: A Timeout is raised if there was a request timeout.
             TooManyRedirects: A TooManyRedirects is raised if the request
                 exceeds the configured number of maximum redirections
             ValueError: A ValueError is raised when there is no valid
                 CVP session.  This occurs because the previous get or post
                 request failed and no session could be established to a
                 CVP node.  Destroy the class and re-instantiate.
     '''
     # Remove any previous session id from the headers
     self.headers.pop('APP_SESSION_ID', None)
     if self.api_token is not None:
         return self._set_headers_api_token()
     elif self.is_cvaas:
         raise CvpLoginError('CVaaS only supports API token authentication.'
                             ' Please create an API token and provide it'
                             ' via the api_token parameter in combination'
                             ' with the is_cvaas parameter')
     return self._login_on_prem()
Ejemplo n.º 2
0
    def connect(self,
                nodes,
                username,
                password,
                connect_timeout=10,
                protocol='https',
                port=None,
                cert=False):
        ''' Login to CVP and get a session ID and cookie.  Currently
            certificates are not verified if the https protocol is specified. A
            warning may be printed out from the requests module for this case.

            Args:
                nodes (list): A list of hostname/IP addresses for CVP nodes
                username (str): The CVP username
                password (str): The CVP password
                connect_timeout (int): The number of seconds to wait for a
                    connection.
                protocol (str): The protocol to use to connect to CVP.
                    THIS PARAMETER IS NOT USED AND WILL BE DEPRECATED.
                    ONLY INCLUDED TO NOT BREAK EXISTING CODE THAT HAS PROTOCOL
                    SPECIFIED IN CONNECTION.
                port (int): The TCP port of the endpoint for the connection.
                    If this keyword is not specified, the default value is
                    automatically determined by the transport type.
                    (http=80, https=443)
                cert (str or boolean): Path to a cert file used for a https
                    connection or boolean with default False. If a cert is
                    provided then the connection will not attempt to fallback
                    to http. The False default sets the request to not verify
                    the servers TLS certificate.

            Raises:
                CvpLoginError: A CvpLoginError is raised if a connection
                    could not be established to any of the nodes.
                TypeError: A TypeError is raised if the nodes argument is not
                    a list.
                ValueError: A ValueError is raised if a port is not specified
                    and the protocol is not http or https.
        '''
        # pylint: disable=too-many-arguments
        if not isinstance(nodes, list):
            raise TypeError('nodes argument must be a list')

        self.cert = cert
        self.nodes = nodes
        self.node_cnt = len(nodes)
        self.node_pool = cycle(nodes)
        self.authdata = {'userId': username, 'password': password}
        self.connect_timeout = connect_timeout
        # protocol is deprecated and not used.
        self.protocol = protocol
        self.port = port
        self._create_session(all_nodes=True)
        # Verify that we can connect to at least one node
        if not self.session:
            raise CvpLoginError(self.error_msg)
Ejemplo n.º 3
0
    def connect(self,
                nodes,
                username,
                password,
                connect_timeout=10,
                protocol='http',
                port=None):
        ''' Login to CVP and get a session ID and cookie.  Currently
            certificates are not verified if the https protocol is specified. A
            warning may be printed out from the requests module for this case.

            Args:
                nodes (list): A list of hostname/IP addresses for CVP nodes
                username (str): The CVP username
                password (str): The CVP password
                connect_timeout (int): The number of seconds to wait for a
                    connection.
                protocol (str): The type of protocol to use for the connection.
                    The default value is 'http'.
                port (int): The TCP port of the endpoint for the connection.
                    If this keyword is not specified, the default value is
                    automatically determined by the transport type.
                    (http=80, https=443)

            Raises:
                CvpLoginError: A CvpLoginError is raised if a connection
                    could not be established to any of the nodes.
                TypeError: A TypeError is raised if the nodes argument is not
                    a list.
                ValueError: A ValueError is raised if a port is not specified
                    and the protocol is not http or https.
        '''
        # pylint: disable=too-many-arguments
        if not isinstance(nodes, list):
            raise TypeError('nodes argument must be a list')

        self.nodes = nodes
        self.node_cnt = len(nodes)
        self.node_pool = cycle(nodes)
        self.authdata = {'userId': username, 'password': password}
        self.connect_timeout = connect_timeout
        self.protocol = protocol

        if port is None:
            if protocol == 'http':
                port = 80
            elif protocol == 'https':
                port = 443
            else:
                raise ValueError('No default port for protocol: %s' % protocol)
        self.port = port

        self._create_session(all_nodes=True)
        # Verify that we can connect to at least one node
        if not self.session:
            raise CvpLoginError(self.error_msg)
def test_connect_fail(mock_client_connect):
    ''' Test connect failure with login error.
    '''
    module = mock.Mock()
    module.params = dict(host='host',
                         username='******',
                         password='******',
                         protocol='https',
                         port='10')
    mock_client_connect.side_effect = CvpLoginError('Login Error')
    client = cv_server_provision.connect(module)
    assert_is_instance(client, CvpClient)
    mock_client_connect.assert_called_once()
    module.fail_json.assert_called_once_with(msg='Login Error')
Ejemplo n.º 5
0
    def connect(self, nodes, username, password, connect_timeout=10,
                request_timeout=30, protocol='https', port=None, cert=False,
                is_cvaas=False, tenant=None, api_token=None, cvaas_token=None):
        ''' Login to CVP and get a session ID and cookie.  Currently
            certificates are not verified if the https protocol is specified. A
            warning may be printed out from the requests module for this case.

            Args:
                nodes (list): A list of hostname/IP addresses for CVP nodes
                username (str): The CVP username
                password (str): The CVP password
                connect_timeout (int): The number of seconds to wait for a
                    connection.
                request_timeout (int): The default number of seconds to allow
                    api requests to complete before timing out.
                protocol (str): The protocol to use to connect to CVP.
                    THIS PARAMETER IS NOT USED AND WILL BE DEPRECATED.
                    ONLY INCLUDED TO NOT BREAK EXISTING CODE THAT HAS PROTOCOL
                    SPECIFIED IN CONNECTION.
                port (int): The TCP port of the endpoint for the connection.
                    If this keyword is not specified, the default value is
                    automatically determined by the transport type.
                    (http=80, https=443)
                cert (str or boolean): Path to a cert file used for a https
                    connection or boolean with default False. If a cert is
                    provided then the connection will not attempt to fallback
                    to http. The False default sets the request to not verify
                    the servers TLS certificate.
                is_cvaas (boolean): Flag for enabling connection to CVaaS.
                tenant: (string): Tenant/Org within CVaaS to connect to.
                    Required if is_cvaas is enabled.
                cvaas_token (string): API Token to use in place of UN/PW login
                    for CVaaS.
                api_token (string): API Token to use in place of UN/PW login
                    for CVP 2020.3.0 and beyond.

            Raises:
                CvpLoginError: A CvpLoginError is raised if a connection
                    could not be established to any of the nodes.
                TypeError: A TypeError is raised if the nodes argument is not
                    a list.
                ValueError: A ValueError is raised if a port is not specified
                    and the protocol is not http or https.
        '''
        # pylint: disable=too-many-arguments
        if not isinstance(nodes, list):
            raise TypeError('nodes argument must be a list')

        for idx, _ in enumerate(nodes):
            if (os.environ.get('CURRENT_NODE_IP') and
                    nodes[idx] in ['127.0.0.1', 'localhost']):
                # We set this env in script-executor container.
                # Mask localhost or 127.0.0.1 with node IP if this
                # is called from configlet builder scripts.
                nodes[idx] = os.environ.get('CURRENT_NODE_IP')

        self.cert = cert
        self.nodes = nodes
        self.node_cnt = len(nodes)
        self.node_pool = cycle(nodes)
        self.authdata = {'userId': username, 'password': password}
        self.connect_timeout = connect_timeout
        self.api.request_timeout = request_timeout
        # protocol is deprecated and not used.
        self.protocol = protocol
        self.port = port
        self.is_cvaas = is_cvaas
        self.tenant = tenant
        if cvaas_token is not None:
            self.log.warning('The cvaas_token parameter will be deprecated'
                             ' soon. Please start using the api_token'
                             ' parameter instead. It provides the same'
                             ' functionality that was previously provided'
                             ' by cvaas_token. The api_token parameter is'
                             ' a more general API token parameter because'
                             ' using the CVP REST API via token is also'
                             ' available for on premises CVP as of'
                             ' CVP version 2020.3.0')
            self.cvaas_token = cvaas_token
            self.api_token = cvaas_token
        if api_token is not None:
            self.log.warning('Using the new api_token parameter.'
                             ' This will override usage of the cvaas_token'
                             ' parameter if both are provided. This is because'
                             ' api_token and cvaas_token parameters are for'
                             ' the same use case and api_token is more'
                             ' generic')
            self.api_token = api_token
            self.cvaas_token = api_token
        self._create_session(all_nodes=True)
        # Verify that we can connect to at least one node
        if not self.session:
            raise CvpLoginError(self.error_msg)