def get_service_root():
    """Gets ServiceRoot

        Recover OneView UUID from appliance and creates
        ServiceRoot redfish JSON
    """

    try:
        ov_ip = config.get_oneview_multiple_ips()[0]
        appliance_node_information = \
            connection.request_oneview(ov_ip,
                                       '/rest/appliance/nodeinfo/version')
        uuid = appliance_node_information['uuid']

        sr = ServiceRoot(uuid)
        json_str = sr.serialize()
        return Response(response=json_str,
                        status=200,
                        mimetype='application/json')
    except HPOneViewException as e:
        if e.oneview_response['errorCode'] == "RESOURCE_NOT_FOUND":
            logging.exception("Resource not found: {}".format(e))
            abort(status.HTTP_404_NOT_FOUND, "Appliance not found")
        else:
            logging.exception("OneView Exception: {}".format(e))
            abort(status.HTTP_500_INTERNAL_SERVER_ERROR)
    except Exception as e:
        logging.exception('ServiceRoot error: {}'.format(e))
        abort(status.HTTP_500_INTERNAL_SERVER_ERROR)
Exemple #2
0
def query_ov_client_by_resource(resource_id, resource, function, *args,
                                **kwargs):
    """Query resource on OneViews.

        Query specific resource ID on multiple OneViews.
        Look resource ID on cached map ResourceID->OneViewIP for query
        on specific cached OneView IP.
        If the resource ID is not cached yet it searches on all OneViews.

        Returns:
            dict: OneView resource
    """
    # Get OneView's IP in the single OneView context
    single_oneview_ip = single.is_single_oneview_context() and \
        single.get_single_oneview_ip()
    # Get OneView's IP for cached resource ID
    cached_oneview_ip = get_ov_ip_by_resource(resource_id)

    # Get OneView's IP in the single OneView context or cached by resource ID
    ip_oneview = single_oneview_ip or cached_oneview_ip

    # If resource is not cached yet search in all OneViews
    if not ip_oneview:
        return search_resource_multiple_ov(resource, function, resource_id,
                                           None, *args, **kwargs)

    # If it's Single Oneview context and no IP is saved on context yet
    if single.is_single_oneview_context() and not single_oneview_ip:
        single.set_single_oneview_ip(ip_oneview)

    ov_client = client_session.get_oneview_client(ip_oneview)

    try:
        resp = execute_query_ov_client(ov_client, resource, function, *args,
                                       **kwargs)
    except HPOneViewException as e:
        if e.oneview_response["errorCode"] not in NOT_FOUND_ONEVIEW_ERRORS:
            raise

        cleanup_map_resources_entry(resource_id)
        ov_ips = config.get_oneview_multiple_ips()
        ov_ips.remove(ip_oneview)  # just search in the other ips

        if not ov_ips:
            raise

        return search_resource_multiple_ov(resource, function, resource_id,
                                           ov_ips, *args, **kwargs)

    # If it's on Single OneView Context and the resource is not
    # mapped to an OneView IP, then we update cache in advance for
    # future requests for this resource
    if single_oneview_ip and not cached_oneview_ip:
        set_map_resources_entry(resource_id, single_oneview_ip)

    return resp
def init_event_service(token=None):
    # Iterate through each ov and fork a new thread to listen scmb
    list_ov_ips = config.get_oneview_multiple_ips()

    for ov_ip in list_ov_ips:
        # Loading scmb connection
        # If scmb connection is already present for respective ov then
        # do not fork new thread to listen scmb
        if ov_ip not in _get_map_scmb_connections():
            scmb_thread = SCMB(ov_ip, config.get_credentials(), token)
            scmb_thread.daemon = True
            scmb_thread.start()
Exemple #4
0
    def test_post_session(self, get_authentication_mode, oneview_client_mockup,
                          uuid_mock):
        """Tests post Session"""

        # Loading Session mockup result
        with open('oneview_redfish_toolkit/mockups/redfish/Session.json') as f:
            expected_session_mockup = json.load(f)

        client_session.init_map_clients()
        multiple_oneview.init_map_appliances()
        get_authentication_mode.return_value = 'session'

        # Create mock response
        uuid_mock.uuid4.return_value = self.session_id
        oneview_client = oneview_client_mockup()
        oneview_client.connection.get_session_id.return_value = self.token_id

        # POST Session
        response = self.client.post("/redfish/v1/SessionService/Sessions",
                                    data=json.dumps(
                                        dict(UserName="******",
                                             Password="******")),
                                    content_type='application/json')

        # Gets json from response
        result = json.loads(response.data.decode("utf-8"))

        # Tests response
        self.assertEqual(status.HTTP_200_OK, response.status_code)
        self.assertEqual("application/json", response.mimetype)
        self.assertEqualMockup(expected_session_mockup, result)
        self.assertIn("/redfish/v1/SessionService/Sessions/" + self.session_id,
                      response.headers["Location"])
        self.assertEqual(self.token_id, response.headers["X-Auth-Token"])
        oneview_client_mockup.assert_called_with({
            'ip':
            config.get_oneview_multiple_ips()[0],
            'credentials': {
                'userName': '******',
                'password': '******'
            },
            'api_version':
            config.get_api_version()
        })

        # gets the session by id
        response_of_get = self.client.get(response.headers["Location"],
                                          content_type='application/json')

        result_of_get = json.loads(response_of_get.data.decode("utf-8"))

        self.assertEqual(status.HTTP_200_OK, response_of_get.status_code)
        self.assertEqual(self.session_id, result_of_get["Id"])
Exemple #5
0
def get_oneview_client():
    # Workaround for #328
    # Create OneView client using API 500 just to retrieve OneView certificates
    ov_config = connection.create_oneview_config(
        # TODO(victorhugorodrigues): Remove after implementation for handling
        # multiple OneViews for events service
        ip=config.get_oneview_multiple_ips()[0],
        credentials=config.get_credentials(),
        api_version=300
    )
    ov_client = OneViewClient(ov_config)
    ov_client.connection.login(config.get_credentials())

    return ov_client
    def test_post_session_with_login_domain_data(self, get_authentication_mode,
                                                 oneview_client_mockup,
                                                 uuid_mock):
        """Tests post Session when UserName has login domain information"""

        with open('oneview_redfish_toolkit/mockups/redfish/'
                  'SessionForLoginWithDomain.json') as f:
            expected_session_mockup = json.load(f)

        client_session.init_map_clients()
        multiple_oneview.init_map_appliances()
        get_authentication_mode.return_value = 'session'

        # Create mock response
        uuid_mock.uuid4.return_value = self.session_id
        oneview_client = oneview_client_mockup()
        oneview_client.connection.get_session_id.return_value = self.token_id

        # POST Session
        response = self.client.post("/redfish/v1/SessionService/Sessions",
                                    data=json.dumps(
                                        dict(UserName="******",
                                             Password="******")),
                                    content_type='application/json')

        # Gets json from response
        result = json.loads(response.data.decode("utf-8"))

        # Tests response
        self.assertEqual(status.HTTP_201_CREATED, response.status_code)
        self.assertEqual("application/json", response.mimetype)
        self.assertEqualMockup(expected_session_mockup, result)
        self.assertIn("/redfish/v1/SessionService/Sessions/" + self.session_id,
                      response.headers["Location"])
        self.assertEqual(self.token_id, response.headers["X-Auth-Token"])
        oneview_client_mockup.assert_called_with({
            'ip':
            config.get_oneview_multiple_ips()[0],
            'credentials': {
                'userName': '******',
                'password': '******',
                'authLoginDomain': 'LOCAL'
            },
            'api_version':
            config.get_api_version()
        })
Exemple #7
0
def scmb_connect():
    # TODO(victorhugorodrigues): Remove after implementation for handling
    # multiple OneViews for events service
    scmb_server = config.get_oneview_multiple_ips()[0]

    # Setup our ssl options
    ssl_options = ({'ca_certs': _oneview_ca_path(),
                    'certfile': _scmb_cert_path(),
                    'keyfile': _scmb_key_path(),
                    'cert_reqs': ssl.CERT_REQUIRED,
                    'server_side': False})

    scmb_connection = pika.BlockingConnection(
        pika.ConnectionParameters(
            scmb_server,
            SCMB_PORT,
            credentials=ExternalCredentials(),
            socket_timeout=SCMB_SOCKET_TIMEOUT,
            ssl=True,
            ssl_options=ssl_options))

    return scmb_connection
Exemple #8
0
def search_resource_multiple_ov(resource, function, resource_id, ov_ips, *args,
                                **kwargs):
    """Search resource on multiple OneViews

        Query resource on all OneViews.
        If it's looking for a specific resource:
            -Once resource is found it will cache the resource ID for the
                OneView's IP that was found;
            -If it is not found return NotFound exception.
        If it's looking for all resources(get_all):
            -Always query on all OneViews and return a list appended the
                results for all OneViews

        Args:
            resource: resource type (server_hardware)
            function: resource function name (get_all)
            resource_id: set only if it should look for a specific resource ID
            ov_ips: List of Oneview IPs to search for the resource.
                If None is passed, it will search in all IPs based on the
                toolkit configuration.
            *args: original arguments for the OneView client query
            **kwargs: original keyword arguments for the OneView client query

        Returns:
            OneView resource(s)

        Exceptions:
            HPOneViewException: When occur an error on any OneViews which is
            not an not found error.
    """
    result = []
    error_not_found = []
    single_oneview_ip = single.is_single_oneview_context() and \
        single.get_single_oneview_ip()

    # If it's on Single Oneview Context and there is already an OneView IP
    # on the context, then uses it. If not search on All OneViews
    if not ov_ips and single_oneview_ip:
        list_ov_ips = [single_oneview_ip]
    else:
        list_ov_ips = ov_ips or config.get_oneview_multiple_ips()

    # Loop in all OneView's IP
    for ov_ip in list_ov_ips:

        ov_client = client_session.get_oneview_client(ov_ip)

        try:
            # Query resource on OneView
            expected_resource = \
                execute_query_ov_client(ov_client, resource, function,
                                        *args, **kwargs)

            if expected_resource:
                # If it's looking for a especific resource and was found
                if resource_id:
                    set_map_resources_entry(resource_id, ov_ip)

                    # If it's SingleOneviewContext and there is no OneView IP
                    # on the context, then set OneView's IP on the context
                    if single.is_single_oneview_context() and \
                            not single_oneview_ip:
                        single.set_single_oneview_ip(ov_ip)

                    return expected_resource
                else:
                    # If it's looking for a resource list (get_all)
                    if isinstance(expected_resource, list):
                        result.extend(expected_resource)
                    else:
                        result.append(expected_resource)
        except HPOneViewException as exception:
            # If get any error that is not a notFoundError
            if exception.oneview_response["errorCode"] not in \
                    NOT_FOUND_ONEVIEW_ERRORS:
                logging.exception("Error while searching on multiple "
                                  "OneViews for Oneview {}: {}".format(
                                      ov_ip, exception))
                raise exception

            error_not_found.append(exception)

    # If it's looking for a specific resource returns a NotFound exception
    if resource_id and error_not_found:
        raise error_not_found.pop()

    return result