예제 #1
0
    def get_zone_ids_by_templates(self, server_profile_templates):
        """Returns the Zone IDs by each Server Profile Template inside the list:

            If the list is empty, the result will be empty

            Args:
                server_profile_templates: the list of Server Profile Template
        """
        zone_ids = []
        enclosure_uris_with_valid_drive_enclosures = \
            self._get_enclosures_uris_with_valid_drive_enclosures()
        logical_encl_list = self.ov_client.logical_enclosures.get_all()
        for template in server_profile_templates:
            template_id = template["uri"].split("/")[-1]
            controller = ComputerSystemService.get_storage_controller(template)
            if controller:
                enclosures_uris_by_spt = self._get_enclosures_uris_by_template(
                    template, logical_encl_list)
                enclosures_uris = set(enclosures_uris_by_spt)\
                    .intersection(enclosure_uris_with_valid_drive_enclosures)

                for encl_uri in sorted(enclosures_uris):
                    zone_id = ZoneService.build_zone_id(template_id, encl_uri)
                    zone_ids.append(zone_id)
            else:
                zone_ids.append(template_id)

        return zone_ids
예제 #2
0
    def __init__(self,
                 resource_id,
                 profile_template,
                 server_hardware_list,
                 enclosure_name,
                 drives=[],
                 volume_list=[]):
        """Zone constructor

            Populates self.redfish with the contents of
            server profile template and server hardware list from Oneview

            Args:
                resource_id: The resource id
                profile_template: Oneview's server profile template dict
                server_hardware_list: Oneview's server hardware list
                (servers and empty bays) for assignment to a server profile
                enclosure_name: Enclosure name associated with a Zone.
                If Zone has not enclosure it will be None.
                drives: Oneview's dict drives list
                volume_list: Oneview's storage volume list
        """
        super().__init__(self.SCHEMA_NAME)

        has_valid_controller = \
            ComputerSystemService.get_storage_controller(profile_template)

        if not has_valid_controller:
            drives = []

        self.redfish["@odata.type"] = self.get_odata_type()
        self.redfish["Id"] = resource_id
        self.redfish["Name"] = self.get_zone_name(
            profile_template["name"], enclosure_name)
        status_from_ov = profile_template["status"]
        self.redfish["Status"] = status_mapping.STATUS_MAP[status_from_ov]

        self.redfish["Links"] = dict()
        self.redfish["Links"]["ResourceBlocks"] = list()

        self.fill_resource_blocks(profile_template, server_hardware_list,
                                  drives, volume_list)

        self.capabilities_key = "@Redfish.CollectionCapabilities"
        self.redfish[self.capabilities_key] = dict()
        self.redfish[self.capabilities_key]["@odata.type"] = \
            self.get_odata_type_by_schema('CollectionCapabilities')
        self.redfish[self.capabilities_key]["Capabilities"] = list()

        self.fill_capabilities_collection(profile_template)

        self.redfish["@odata.context"] = "/redfish/v1/$metadata#Zone.Zone"
        self.redfish["@odata.id"] = ZoneCollection.BASE_URI + "/" +\
            self.redfish["Id"]

        self._validate()
def remove_computer_system(uuid):
    """Removes a specific System

        Args:
            uuid: The System ID.
    """
    try:
        profile = g.oneview_client.server_profiles.get_by_id(uuid).data
    except HPOneViewException as e:
        abort(status.HTTP_404_NOT_FOUND, e.msg)

    sh_uuid = profile['serverHardwareUri']
    if sh_uuid:
        service = ComputerSystemService(g.oneview_client)
        service.power_off_server_hardware(sh_uuid)

    # Deletes server profile for given UUID
    response = None
    try:
        response = g.oneview_client.server_profiles.delete(uuid)
    except HPOneViewTaskError as e:
        abort(status.HTTP_403_FORBIDDEN, e.msg)

    if response is True:
        return Response(status=status.HTTP_204_NO_CONTENT,
                        mimetype="application/json")

    # Check if returned a task
    if type(response) is dict:
        # Check if task is completed
        if response['taskState'] == 'Completed':
            return Response(status=status.HTTP_204_NO_CONTENT,
                            mimetype="application/json")

        # Log task error messages if it has
        if response['taskState'] in TASK_ERROR_STATES and \
            'taskErrors' in response and len(response['taskErrors']) > 0:
            for err in response['taskErrors']:
                if 'message' in err:
                    logging.exception(err['message'])

    abort(status.HTTP_500_INTERNAL_SERVER_ERROR)
def get_computer_system(uuid):
    """Get the Redfish Computer System for a given UUID.

        Return ComputerSystem redfish JSON for a given
        server profile or server profile template UUID.

        Returns:
            JSON: Redfish json with ComputerSystem
            When Server hardware or Server profilte templates
            is not found calls abort(404)
    """

    resource = _get_oneview_resource(uuid)
    category = resource["category"]

    if category == 'server-profile-templates':
        computer_system_resource = CapabilitiesObject(resource)
    elif category == 'server-profiles':
        server_hardware = g.oneview_client.server_hardware\
            .get_by_uri(resource["serverHardwareUri"]).data
        server_hardware_type = g.oneview_client.server_hardware_types\
            .get_by_uri(resource['serverHardwareTypeUri']).data

        computer_system_service = ComputerSystemService(g.oneview_client)
        drives = _get_drives_from_sp(resource)
        spt_uuid = computer_system_service.\
            get_server_profile_template_from_sp(resource["uri"])

        # Get external storage volumes from server profile
        volumes_uris = [
            volume["volumeUri"]
            for volume in resource["sanStorage"]["volumeAttachments"]
        ]

        # Emptying volume list to suppress external storage changes for
        # current release.
        # In future, remove this line to enable external storage support
        volumes_uris = []

        manager_uuid = get_manager_uuid(resource['serverHardwareTypeUri'])

        # Build Computer System object and validates it
        computer_system_resource = ComputerSystem.build_composed_system(
            server_hardware, server_hardware_type, resource, drives, spt_uuid,
            manager_uuid, volumes_uris)
    else:
        abort(status.HTTP_404_NOT_FOUND,
              'Computer System UUID {} not found'.format(uuid))

    return ResponseBuilder.success(computer_system_resource,
                                   {"ETag": "W/" + resource["eTag"]})
예제 #5
0
def get_computer_system(uuid):
    """Get the Redfish Computer System for a given UUID.

        Return ComputerSystem redfish JSON for a given
        server profile or server profile template UUID.

        Returns:
            JSON: Redfish json with ComputerSystem
            When Server hardware or Server profilte templates
            is not found calls abort(404)
    """

    resource = _get_oneview_resource(uuid)
    category = resource["category"]

    if category == 'server-profile-templates':
        computer_system_resource = CapabilitiesObject(resource)
    elif category == 'server-profiles':
        server_hardware = g.oneview_client.server_hardware\
            .get(resource["serverHardwareUri"])
        server_hardware_type = g.oneview_client.server_hardware_types\
            .get(resource['serverHardwareTypeUri'])

        computer_system_service = ComputerSystemService(g.oneview_client)
        drives = _get_drives_from_sp(resource)
        spt_uuid = computer_system_service.\
            get_server_profile_template_from_sp(resource["uri"])

        manager_uuid = get_manager_uuid(resource['serverHardwareTypeUri'])

        # Build Computer System object and validates it
        computer_system_resource = ComputerSystem.build_composed_system(
            server_hardware,
            server_hardware_type,
            resource,
            drives,
            spt_uuid,
            manager_uuid)
    else:
        abort(status.HTTP_404_NOT_FOUND,
              'Computer System UUID {} not found'.format(uuid))

    return ResponseBuilder.success(
        computer_system_resource,
        {"ETag": "W/" + resource["eTag"]})
    def _build_sas_logical_jbods(profile_name, server_profile_template,
                                 storage_blocks):
        sas_logical_jbods = []

        controller = ComputerSystemService.get_storage_controller(
            server_profile_template)

        if storage_blocks and not controller:
            raise OneViewRedfishInvalidConditionException(
                "The Server Profile Template should have a valid storage "
                "controller to use the Storage Resource Blocks passed")

        for index, storage_block in enumerate(storage_blocks):
            storage_id = index + 1
            attributes = storage_block["attributes"]

            storage = {
                "id":
                storage_id,
                "name":
                profile_name + " - Storage " + str(storage_id),
                "deviceSlot":
                controller["deviceSlot"],
                "numPhysicalDrives":
                1,
                "driveMinSizeGB":
                attributes["capacityInGB"],
                "driveMaxSizeGB":
                attributes["capacityInGB"],
                "driveTechnology":
                attributes["interfaceType"].capitalize() +
                attributes["mediaType"].capitalize()
            }

            sas_logical_jbods.append(storage)

        return sas_logical_jbods
예제 #7
0
def create_composed_system():
    if not request.is_json:
        abort(status.HTTP_400_BAD_REQUEST,
              "The request content should be a valid JSON")

    body = request.get_json()
    result_location_uri = None

    try:
        RedfishJsonValidator.validate(body, 'ComputerSystem')
        service = ComputerSystemService(g.oneview_client)

        blocks = body["Links"]["ResourceBlocks"]
        block_ids = [block["@odata.id"].split("/")[-1] for block in blocks]

        # Should contain only one computer system entry
        system_blocks = _get_system_resource_blocks(block_ids)
        if not system_blocks:
            raise ValidationError(
                "Should have a Computer System Resource Block")

        system_block = system_blocks[0]
        service.validate_computer_system_resource_block_to_composition(
            system_block)

        # Check network block id with the Id attribute in the request
        network_blocks = _get_network_resource_blocks(block_ids)
        spt_id = body["Id"]

        if not (network_blocks and spt_id in network_blocks[0]["uri"]):
            raise ValidationError(
                "Should have a valid Network Resource Block")

        # It can contain zero or more Storage Block
        storage_blocks = _get_storage_resource_blocks(block_ids)

        spt = g.oneview_client.server_profile_templates.get(spt_id)

        server_profile = ComputerSystem.build_server_profile(
            body["Name"],
            body.get("Description"),
            spt,
            system_block,
            network_blocks,
            storage_blocks)

        service.power_off_server_hardware(system_block["uuid"],
                                          on_compose=True)

        task, resource_uri = service.create_composed_system(server_profile)

        if resource_uri:
            result_uuid = resource_uri.split("/")[-1]
            result_location_uri = ComputerSystem.BASE_URI + "/" + result_uuid
            server_profile_label = dict(
                resourceUri=resource_uri, labels=[spt_id.replace("-", " ")])
            g.oneview_client.labels.create(server_profile_label)
        elif task.get("taskErrors"):
            err_msg = reduce(
                lambda result, msg: result + msg["message"] + "\n",
                task["taskErrors"],
                "")
            abort(status.HTTP_403_FORBIDDEN, err_msg)

    except ValidationError as e:
        abort(status.HTTP_400_BAD_REQUEST, e.message)
    except KeyError as e:
        abort(status.HTTP_400_BAD_REQUEST,
              "Trying access an invalid key {}".format(e.args))
    except HPOneViewTaskError as e:
        abort(status.HTTP_403_FORBIDDEN, e.msg)

    if not result_location_uri:
        logging.error("It was not possible get the server profile URI when "
                      "creating a composed system")
        abort(status.HTTP_500_INTERNAL_SERVER_ERROR)

    return Response(status=status.HTTP_201_CREATED,
                    headers={"Location": result_location_uri},
                    mimetype="application/json")