def get_manager_collection():
    """Get the Redfish Manager Collection.

        Return ManagerCollection redfish JSON.
        Logs exception of any error and return
        Internal Server Error or Not Found.

        Returns:
            JSON: Redfish json with ManagerCollection.
            When Server hardware or enclosures is not found
            calls abort(404).

        Exceptions:
            OneViewRedfishResourceNotFoundError: if have some oneview resource
            with empty value (ServerHardware or Enclosures).
            Logs the exception and call abort(404).

            Exception: Generic error, logs the exception and call abort(500).
    """

    try:
        # Gets all enclosures
        enclosures = g.oneview_client.enclosures.get_all()

        if not enclosures:
            raise OneViewRedfishResourceNotFoundError("enclosures", "Resource")

        # Gets all server hardware
        server_hardware_list = g.oneview_client.server_hardware.get_all()

        if not server_hardware_list:
            raise OneViewRedfishResourceNotFoundError("server-hardware-list",
                                                      "Resource")

        # Build Manager Collection object and validates it
        mc = ManagerCollection(server_hardware_list, enclosures)

        # Build redfish json
        json_str = mc.serialize()
        # Build response and returns
        return Response(response=json_str,
                        status=status.HTTP_200_OK,
                        mimetype="application/json")

    except OneViewRedfishResourceNotFoundError as e:
        # In case of error print exception and abort
        logging.exception(e)
        abort(status.HTTP_404_NOT_FOUND, e.msg)

    except Exception as e:
        # In case of error print exception and abort
        logging.exception('Unexpected error: {}'.format(e))
        abort(status.HTTP_500_INTERNAL_SERVER_ERROR)
def get_network_port(uuid, device_id, port_id):
    """Get the Redfish NetworkPort for a given UUID, device_id and port_id.

        Return NetworkPort Redfish JSON for a given hardware UUID, device_id
        and port_id.

        Parameters:
            uuid: the UUID of the server_hardware
            device_id: The id of the network device
            port_id: The id of the port

        Returns:
            JSON: Redfish json with NetworkPort

        Exceptions:
            When hardware is not found calls abort(404)
            When other errors occur calls abort(500)

    """
    try:
        # Initial validation of device_id
        device_id_validation = int(device_id)

        server_hardware = g.oneview_client.server_hardware.get(uuid)

        # Final validation of device_id
        if device_id_validation - 1 < 0 or (device_id_validation - 1) >= \
            len(server_hardware["portMap"]["deviceSlots"]):
            raise OneViewRedfishResourceNotFoundError(device_id,
                                                      "Network adapter")

        np = NetworkPort(device_id, port_id, server_hardware)

        json_str = np.serialize()

        return Response(response=json_str,
                        status=status.HTTP_200_OK,
                        mimetype="application/json")
    except ValueError:
        # Failed to convert device_id to int
        logging.exception(
            "Failed to convert device id {} to integer.".format(device_id))
        abort(status.HTTP_404_NOT_FOUND, "Network adapter not found")
    except OneViewRedfishResourceNotFoundError as e:
        logging.exception(e.msg)
        abort(status.HTTP_404_NOT_FOUND, e.msg)
    except OneViewRedfishError as e:
        logging.exception(e.msg)
        abort(status.HTTP_404_NOT_FOUND, e.msg)
    except HPOneViewException as e:
        # In case of error log exception and abort
        logging.exception(e)
        if e.oneview_response['errorCode'] == "RESOURCE_NOT_FOUND":
            abort(status.HTTP_404_NOT_FOUND, "Server hardware not found")
        else:
            abort(status.HTTP_500_INTERNAL_SERVER_ERROR)
    except Exception as e:
        # In case of error log exception and abort
        logging.exception('Unexpected error: {}'.format(e))
        abort(status.HTTP_500_INTERNAL_SERVER_ERROR)
def store_schemas(schema_dir):
    """Stores all DMTF JSON Schemas

        Stores all schemas listed in schemas searching schema_dir directory.

        Args:
            schema_dir: String with the directory to load schemas from.

        Returns:
            Dictionary: A dict containing ('http://redfish.dmtf.org/schemas/
                        v1/<schema_file_name>': schema_obj) pairs
    """
    schema_paths = glob.glob(schema_dir + '/*.json')

    if not schema_paths:
        raise OneViewRedfishResourceNotFoundError("JSON Schemas", "File")

    stored_schemas = dict()

    for path in schema_paths:
        with open(path) as schema_file:
            json_schema = json.load(schema_file)

        if os.name == 'nt':
            file_name = path.split('\\')[-1]
        else:
            file_name = path.split('/')[-1]
        stored_schemas["http://redfish.dmtf.org/schemas/v1/" + file_name] = \
            json_schema

    globals()['stored_schemas'] = stored_schemas
def load_conf(conf_file):
    """Loads and parses conf file

        Loads and parses the module conf file

        Args:
            conf_file: string with the conf file name

        Returns:
            ConfigParser object with conf_file configs

        Exception:
            OneViewRedfishResourceNotFoundError:
                - if conf file not found
    """

    if not os.path.isfile(conf_file):
        raise OneViewRedfishResourceNotFoundError(conf_file, 'File')

    config = configparser.ConfigParser()
    config.optionxform = str
    try:
        config.read(conf_file)
    except Exception:
        raise

    return config
Esempio n. 5
0
    def get_resource_by_id(self, resource_list, resource_number_key,
                           resource_id):
        """Gets a specific resource in the resource list

            Validates the resource ID and gets the resource in
            the resource list.

            Args:
                resource_list: List of resources.
                resource_number_key: Field name of the resource
                    number in the JSON.
                resource_id: Resource's ID that will be searched
                    in the resource list.

            Returns:
                Resource in the list.

            Exception:
                OneViewRedfishError: If the ID is not an integer.
                OneViewRedfishResourceNotFoundError: If the resource
                    was not found.
        """
        try:
            resource_id = int(resource_id)
        except ValueError:
            raise OneViewRedfishError("Invalid {} ID".format(
                self.__class__.__name__))

        for resource in resource_list:
            if resource[resource_number_key] == resource_id:
                return resource

        raise OneViewRedfishResourceNotFoundError("Object",
                                                  self.__class__.__name__)
def get_computer_system_collection():
    """Get the Redfish Computer System Collection.

        Get method to return ComputerSystemCollection JSON when
        /redfish/v1/Systems is requested.

        Returns:
                JSON: JSON with ComputerSystemCollection.
    """
    try:
        # Gets all server hardware
        server_hardware_list = g.oneview_client.server_hardware.get_all()
        if not server_hardware_list:
            raise OneViewRedfishResourceNotFoundError("server-hardware-list",
                                                      "Resource")

        # Build Computer System Collection object and validates it
        csc = ComputerSystemCollection(server_hardware_list)

        # Build redfish json
        json_str = csc.serialize()

        # Build response and returns
        return Response(response=json_str,
                        status=status.HTTP_200_OK,
                        mimetype="application/json")
    except OneViewRedfishResourceNotFoundError as e:
        # In case of error log exception and abort
        logging.exception('Unexpected error: {}'.format(e))
        abort(status.HTTP_404_NOT_FOUND, e.msg)
    except Exception as e:
        # In case of error print exception and abort
        logging.exception(e)
        return abort(status.HTTP_500_INTERNAL_SERVER_ERROR)
    def __init__(self, device_id, device_function_id, server_hardware):
        """NetworkDeviceFunction constructor

            Populates self.redfish with the contents of server hardware dict
            from Oneview

            Args:
                device_id: ID of the NetworkAdapter
                device_function_id: ID of the DeviceFunction. Expected format:
                    portNumber_virtualPortNumber_virtualPortFunction
                server_hardware: Oneview's server hardware dict
        """
        super().__init__(self.SCHEMA_NAME)

        # device_function_id validation
        try:
            port_number, virtual_port_number, virtual_port_function = \
                device_function_id.split("_")

            physical_ports = self.get_resource_by_id(
                server_hardware["portMap"]["deviceSlots"], "deviceNumber",
                device_id)["physicalPorts"]

            port = self.get_resource_by_id(physical_ports, "portNumber",
                                           port_number)

            virtual_port = self.get_resource_by_id(port["virtualPorts"],
                                                   "portNumber",
                                                   virtual_port_number)
        except Exception:
            raise OneViewRedfishResourceNotFoundError(device_function_id,
                                                      "NetworkDeviceFunction")

        self.redfish["@odata.type"] = \
            "#NetworkDeviceFunction.v1_1_0.NetworkDeviceFunction"
        self.redfish["Id"] = device_function_id
        self.redfish["Name"] = "Physical port {}, virtual port {}, device "\
            "function {}".format(
                port_number, virtual_port_number, virtual_port_function)

        if port["type"] == "Ethernet":
            self.redfish["Ethernet"] = dict()
            self.redfish["Ethernet"]["MACAddress"] = virtual_port["mac"]
            self.redfish["NetDevFuncType"] = "Ethernet"
        elif port["type"] == "FibreChannel":
            raise OneViewRedfishError("FibreChannel not implemented")
        else:
            raise OneViewRedfishError("Type not supported")

        self.redfish["@odata.context"] = \
            "/redfish/v1/$metadata#NetworkDeviceFunction.NetworkDeviceFunction"
        self.redfish["@odata.id"] = "/redfish/v1/Chassis/" + \
            server_hardware["uuid"] + \
            "/NetworkAdapters/" + device_id + \
            "/NetworkDeviceFunctions/" + device_function_id

        self._validate()
    def add_extended_info(self,
                          message_id,
                          message_args=[],
                          related_properties=[]):
        """Adds an item to ExtendedInfo list using values from DMTF registry

            Adds an item to ExtendedInfo list using the values for Message,
            Severity and Resolution from DMTF Base Registry.

            Parameters:
                message_id: Id of the message; oneOf the keys in Redfish
                    Registry Messages
                message_args: List of string to replace markers on Redfish
                    messages. Must have the same length as the number of %
                    signs found in the registry Message field
                related_properties: Properties relates to this e error if
                    necessary

        """
        messages = util.registry_dict["Base"]["Messages"]

        # Verify if message_id exists in registry
        try:
            severity = messages[message_id]["Severity"]
        except Exception:
            raise OneViewRedfishResourceNotFoundError(message_id, "message_id")

        message = messages[message_id]["Message"]

        # Check if numbers of replacemets and message_args length match
        replaces = message.count('%')
        replacements = len(message_args)
        if replaces != replacements:
            raise OneViewRedfishError(
                'Message has {} replacements to be made but {} args '
                'where sent'.format(replaces, replacements))
        # Replacing the marks in the message. A better way to do this
        # is welcome.
        for i in range(replaces):
            message = message.replace('%' + str(i + 1), message_args[i])

        # Construct the dict
        extended_info = collections.OrderedDict()
        extended_info["@odata.type"] = "#Message.v1_0_5.Message"
        extended_info["MessageId"] = "Base.1.1." + message_id
        extended_info["Message"] = message
        extended_info["RelatedProperties"] = related_properties
        extended_info["MessageArgs"] = message_args
        extended_info["Severity"] = severity
        extended_info["Resolution"] = messages[message_id]["Resolution"]

        # Append it to the list
        self.redfish["error"]["@Message.ExtendedInfo"].append(extended_info)
    def __init__(self, code, message):
        """Constructor

            Populates self.redfish with error message.
        """

        super().__init__(self.SCHEMA_NAME)
        self.redfish["error"] = collections.OrderedDict()
        # Check if Code is a valid Code Error in the registry
        if code not in util.registry_dict["Base"]["Messages"]:
            raise OneViewRedfishResourceNotFoundError(code, "registry")
        self.redfish["error"]["code"] = "Base.1.1." + code
        self.redfish["error"]["message"] = message
        self.redfish["error"]["@Message.ExtendedInfo"] = list()
def load_registry(registry_dir, registries):
    """Loads Registries

        Loads all registries listed in the config file using registry_dir
        directory

        Args:
            registry_dir: string with the directory to load registries from
            registries: dict with registry name as key and registry file_name
                as value. The key will also be the key in the returning dict.

        Returns:
            OrderedDict: A dict containing 'RegistryName': registry_obj

        Exceptions:
            OneviewRedfishResourceNotFoundError:
                - if registry_dir is not found
                - any of json files is not found
            OneviewRedfishResourceNotAccessible:
                - if registry_dir is can't be accessed
    """

    if os.path.isdir(registry_dir) is False:
        raise OneViewRedfishResourceNotFoundError(registry_dir, 'Directory')
    if os.access(registry_dir, os.R_OK) is False:
        raise OneViewRedfishResourceNotAccessibleError(registry_dir,
                                                       'directory')

    registries_dict = collections.OrderedDict()
    for key in registries:
        try:
            with open(registry_dir + '/' + registries[key]) as f:
                registries_dict[key] = json.load(f)
        except Exception:
            raise OneViewRedfishResourceNotFoundError(registries[key], 'File')

    return registries_dict